Python3交互redis cluster(python 交互)

网友投稿 515 2022-08-26


Python3交互redis cluster(python 交互)

安装

pip install redis-py-cluster

示例代码

# pip install redis-py-clusterfrom rediscluster import *"""redis 集群信息:Using 3 masters:192.168.196.131:7000192.168.196.129:7003192.168.196.131:7001Adding replica 192.168.196.129:7004 to 192.168.196.131:7000Adding replica 192.168.196.131:7002 to 192.168.196.129:7003Adding 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-clusterfrom rediscluster import *"""redis 集群信息:Using 3 masters:192.168.196.131:7000192.168.196.129:7003192.168.196.131:7001Adding replica 192.168.196.129:7004 to 192.168.196.131:7000Adding replica 192.168.196.131:7002 to 192.168.196.129:7003Adding 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'))

运行如下:


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python中关于元组三个不常用的特性(关于python的元组类型以下选项)
下一篇:MapStruct表达式应用及避坑详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~