今天使用Python連接Azure Redis的時(shí)候遇到了一系列問題遇八。
首先历帚,使用Python的redis包連接Redis的時(shí)候一切順利姆怪,但是過了一段時(shí)間就報(bào)了Moved Exception为严。這才想起來自己初始化Azure Redis時(shí)開啟了Cluster。
Python連接Redis Cluster到不是什么難事黑低,安裝 redis-py-cluster即可。
$ pip install redis-py-cluster
官方文檔示例配置如下:
>>> from rediscluster import StrictRedisCluster
>>> # Requires at least one node for cluster discovery. Multiple nodes is recommended.
>>> startup_nodes = [{"host": "127.0.0.1", "port": "7000"}]
>>> rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
>>> rc.set("foo", "bar")
True
>>> print(rc.get("foo"))
'bar'
但是這樣配置無法正常連接酌毡,因?yàn)槲疫€配置了Azure Redis Cluster只使用SSL連接克握。redis-py-cluster的文檔雖然沒有使用SSL的示例,但是Release Note里有這么一句:
1.3.4 (Mar 5, 2017)
...
*Add SSLClusterConnection for connecting over TLS/SSL to Redis Cluster
...
所以最新版肯定支持SSL訪問Redis Cluster枷踏。于是直接去GitHub翻代碼菩暗。找到注釋如下:
Manages TCP communication over TLS/SSL to and from a Redis cluster
Usage:
pool = ClusterConnectionPool(connection_class=SSLClusterConnection, ...)
client = StrictRedisCluster(connection_pool=pool)
按此方法調(diào)用后本以為大功告成,但是又返回了新的錯(cuò)誤旭蠕。
redis.exceptions.ResponseError: unknown command: CONFIG
好在微軟官方論壇搜到了答案:
Azure Redis cache doesn't support the CONFIG command, but redis-py-cluster has a workaround for this:
From their release notes for 1.3.2:
If your redis instance is configured to not have the CONFIG ... comannds enabled due to security reasons you need to pass this into the client object skip_full_coverage_check=True. Benefits is that the client class no longer requires the CONFIG ... commands to be enabled on the server. Downsides is that you can't use the option in your redis server and still use the same feature in this client.
同時(shí)因?yàn)椴⒉恍枰渲枚鄠€(gè)節(jié)點(diǎn)停团,所以最終代碼示例如下:
from rediscluster import StrictRedisCluster
from rediscluster.connection import *
startup_nodes = [{"host": "domain", "port": "6380"}]
pool = ClusterConnectionPool(connection_class=SSLClusterConnection, startup_nodes=startup_nodes, password="*****",skip_full_coverage_check=True)
rc = StrictRedisCluster(connection_pool=pool)