安装
pip install redis-py-cluster
示例代码
# pip install redis-py-cluster
from rediscluster import *
"""
redis 集群信息:
Using 3 masters:
192.168.196.131:7000
192.168.196.129:7003
192.168.196.131:7001
Adding replica 192.168.196.129:7004 to 192.168.196.131:7000
Adding replica 192.168.196.131:7002 to 192.168.196.129:7003
Adding replica 192.168.196.129:7005 to 192.168.196.131:7001
"""
if __name__ == '__main__':
try:
# 构建所有的节点,Redis会使⽤CRC16算法,将键和值写到某个节点上
startup_nodes = [
{'host': '192.168.196.131', 'port': '7000'},
{'host': '192.168.196.129', 'port': '7003'},
{'host': '192.168.196.131', 'port': '7001'},
]
# 构建StrictRedisCluster对象
src = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
# 设置键为key1、值为test-hello-world的数据
result = src.set('key1', 'test-hello-world')
print(result)
# 获取键为name
name = src.get('key1')
print(name)
except Exception as e:
print(e)
运行如下:
封装类方法
# pip install redis-py-cluster
from rediscluster import *
"""
redis 集群信息:
Using 3 masters:
192.168.196.131:7000
192.168.196.129:7003
192.168.196.131:7001
Adding replica 192.168.196.129:7004 to 192.168.196.131:7000
Adding replica 192.168.196.131:7002 to 192.168.196.129:7003
Adding replica 192.168.196.129:7005 to 192.168.196.131:7001
"""
class redisClusterHelper():
def __init__(self,startup_nodes):
try:
# 构建StrictRedisCluster对象
self.src = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)
except Exception as e:
print(e)
def set_key(self,key,value):
return self.src.set(key, value)
def get_key(self,key):
return self.src.get(key)
if __name__ == '__main__':
# 设置redis cluster集群的master节点
startup_nodes = [
{'host': '192.168.196.131', 'port': '7000'},
{'host': '192.168.196.129', 'port': '7003'},
{'host': '192.168.196.131', 'port': '7001'},
]
# 创建redis cluster的连接
rch = redisClusterHelper(startup_nodes)
# 设置key值
rch.set_key("test2","hello2")
# 获取key值
print(rch.get_key('test2'))
运行如下:
网友评论