python3 连接redis集群

版本信息

  • python版本 3.7
  • pip install redis==3.5.3
  • pip install redis-py-cluste==2.1.3

集群连接

  1. 单节点连接
    通过集群里面的任意节点连接到集群,连接之后,客户端会向服务器发送cluster slots命令获取集群哈希槽的分布信息。
import random
import rediscluster
import string

cli = rediscluster.RedisCluster(host='192.168.7.41', port=8001, password="")
for i in range(1000):
    cli.set(''.join(random.sample(string.ascii_letters, 10)), i, ex=1200)
print(cli)
cli.close()
  1. 连接池连接
import random
import threading

import rediscluster
from rediscluster import ClusterConnectionPool
import string, time

startup_nodes = [
    {"host": "192.168.7.41", "port": 8001},
]
pool = ClusterConnectionPool(startup_nodes=startup_nodes, password="", max_connections=10, max_connections_per_node=10)
cli = rediscluster.RedisCluster(connection_pool=pool)


def test():
    for i in range(100):
        cli.set(''.join(random.sample(string.ascii_letters, 10)), i, ex=1200)


ths = [threading.Thread(target=test) for n in range(10)]
for t in ths:
    t.start()
for t in ths:
    t.join()
posted @ 2024-03-15 16:10  今夕何兮  阅读(79)  评论(0编辑  收藏  举报