前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3交互redis cluster

Python3交互redis cluster

作者头像
Devops海洋的渔夫
发布2019-06-02 13:24:59
2.3K0
发布2019-06-02 13:24:59
举报
文章被收录于专栏:Devops专栏

安装

pip install redis-py-cluster

示例代码

代码语言:javascript
复制
# 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)

运行如下:

封装类方法

代码语言:javascript
复制
# 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'))

运行如下:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.04.17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装
  • 示例代码
  • 封装类方法
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档