python 连接 redis cluster 集群

一. redis集群模式有多种, cluster模式只是其中的一种实现方式, 其原理请自行谷歌或者百度, 这里只举例如何使用Python操作 redis cluster 集群

二. python 连接 redis cluster 集群

  第三方库:

    redis-py-cluster: 最近还在维护

    rediscluster: 似乎很久没有更新了

pip install redis-py-cluster
or
pip install rediscluster
from rediscluster import StrictRedisCluster
# redis cluster 集群最少三主三从 startup_nodes = [ {"host":"192.168.3.25", "port":6379}, # 主 {"host":"192.168.3.25", "port":7001}, # 6379的从数据库 {"host":"192.168.3.25", "port":6380}, # 主 {"host":"192.168.3.25", "port":7002}, # 6380的从数据库 {"host":"192.168.3.25", "port":6381}, # 主 {"host":"192.168.3.25", "port":7003} # 6381的从数据库 ]
# 连接集群 conn = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
conn.set('name', 'lowman') conn.set('kind', '屌丝')
conn.set('money', '3块8')
print("My name is: ", conn.get('name')) print "I have money: ", conn.get('money')

其他的各项操作方法与 python 的 redis 库保持一致. startup_nodes 参数中即使存在 错误节点参数 也能连接成功: 理论上, 只要保证有一个节点参数正确就可以正常连接