python 连接redis集群和单机
时间: 2023-05-14 22:05:41 浏览: 119
可以使用redis-py-cluster库来连接redis集群,使用redis-py库来连接单机。以下是连接redis集群和单机的示例代码:
连接redis集群:
```
from rediscluster import RedisCluster
startup_nodes = [{"host": "127.0.0.1", "port": "7000"}]
rc = RedisCluster(startup_nodes=startup_nodes, decode_responses=True)
rc.set("key", "value")
print
相关问题
python连接redis集群
在Python中连接Redis集群,可以使用第三方库redis-py-cluster。这个库是专门为了支持Redis集群操作而设计的,并且一直在维护。你可以使用pip进行安装,命令是pip3 install redis-py-cluster。
以下是一个示例代码,展示了如何使用redis-py-cluster连接Redis集群:
```
from rediscluster import StrictRedisCluster
# 连接redis集群
class RedisCluster(object):
def __init__(self,conn_list):
self.conn_list = conn_list
def connect(self):
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集群连接列表
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}]
# 连接Redis集群
res = RedisCluster(redis_basis_conn).connect()
# 检查连接结果
if not res:
print("连接Redis集群失败")
else:
print("连接Redis集群成功")
```
使用redis-py-cluster库,你可以通过传入连接列表中的所有节点信息来连接Redis集群。在上述示例代码中,我们使用了一个名为RedisCluster的类来进行连接,并在初始化方法中传入了连接列表。然后,在connect方法中,我们尝试连接Redis集群,如果连接成功,返回一个Redis连接对象,否则返回False表示连接失败。最后,我们根据连接的结果输出相应的提示信息。
python 连接redis集群设置超时时间
在 Python 中连接 Redis 集群并设置超时时间可以使用 redis-py-cluster 库。
首先,安装 redis-py-cluster 库:
```
pip install redis-py-cluster
```
然后,连接 Redis 集群并设置超时时间:
```python
from rediscluster import RedisCluster
startup_nodes = [
{"host": "127.0.0.1", "port": "7000"},
{"host": "127.0.0.1", "port": "7001"},
{"host": "127.0.0.1", "port": "7002"}
]
# 设置连接超时时间为 5 秒
redis_cluster = RedisCluster(startup_nodes=startup_nodes, socket_timeout=5)
# 使用 redis_cluster 进行操作
redis_cluster.set("key", "value")
```
在上面的代码中,我们通过 RedisCluster 类连接 Redis 集群,并设置 socket_timeout 参数为 5 秒。这样,在连接 Redis 集群时,如果连接超时,则会抛出 redis.exceptions.TimeoutError 异常。