python的redis库是不支持集群操作的,推荐库:redis-py-cluster,一直在维护。还有一个rediscluster库,看GitHub上已经很久没更新了。

安装

pip3 install redis-py-cluster

 

连接redis集群

#!/usr/bin/env python
# coding: utf-8

from rediscluster import StrictRedisCluster

class RedisCluster(object):  # 连接redis集群
    def __init__(self,conn_list):
        self.conn_list = conn_list  # 连接列表

    def connect(self):
        """
        连接redis集群
        :return: object
        """
        try:
            # 非密码连接redis集群
            # redisconn = StrictRedisCluster(startup_nodes=self.conn_list)
            # 使用密码连接redis集群
            redisconn = StrictRedisCluster(startup_nodes=self.conn_list, password='123456')
            return redisconn
        except Exception as e:
            print(e)
            print("错误,连接redis 集群失败")
            return False

redis_basis_conn = [{'host': '192.168.10.168', 'port': 7201}, {'host': '192.168.10.169', 'port': 7201}, {'host': '192.168.10.170', 'port': 7201}, {'host': '192.168.10.171', 'port': 7201}, {'host': '192.168.10.142', 'port': 7201}, {'host': '192.168.10.143', 'port': 7201}]

res = RedisCluster(redis_basis_conn).connect()
if not res:
    print("连接redis集群失败")
else:
    print("连接redis集群成功")
View Code

相关文章: