本文主要是介绍Python3交互redis cluster,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
安装
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)# 获取键为namename = 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'))
运行如下:
这篇关于Python3交互redis cluster的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!