python操作redis集群
1 基础环境分析
redis版本:redis-5.0.14
2 脚本示例
说明:向redis集群里面写入10000000条数据,再查询下这些数据
#!/usr/bin/python3 import random import string import hashlib from rediscluster import RedisCluster import datetime """ 使用redis的方式向redis集群中写入key, 类型为 string pip3 install redis-py-cluster==2.1.3 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com """ #全局 chars = string.ascii_letters + '01234567896' size = 24 ranlong = 10000000 startup_node = [ {"host": "192.168.2.150", "port": 6379}, {"host": "192.168.2.150", "port": 6380}, {"host": "192.168.2.150", "port": 6381}, {"host": "192.168.2.150", "port": 6382}, {"host": "192.168.2.151", "port": 6379}, {"host": "192.168.2.151", "port": 6380}, {"host": "192.168.2.151", "port": 6381}, {"host": "192.168.2.151", "port": 6382}, {"host": "192.168.2.152", "port": 6379}, {"host": "192.168.2.152", "port": 6380}, {"host": "192.168.2.152", "port": 6381}, {"host": "192.168.2.152", "port": 6382} ] def random_string_generator(startup_node,ranlong=10000000,str_size=24, allowed_chars=chars, write=1): starts = datetime.datetime.now() try: redis_conn = RedisCluster(startup_nodes=startup_node, password="", decode_responses=True) #写数据 if write == 1: for i in range(ranlong): String_long = str.lower(''.join(random.choice(allowed_chars) for x in range(str_size))) String_md5s = hashlib.md5(String_long.encode()).hexdigest() redis_conn.set(String_md5s,String_long) else: seconds = (datetime.datetime.now() - starts).total_seconds() print("write second {}".format(seconds)) #读数据 elif write == 0: seconds = (datetime.datetime.now() - starts).total_seconds() stringvalue = redis_conn.get('000000000432ad176430163a3e20d3e') print("read key={0} value={1} second={2}".format('000000000432ad176430163a3e20d3e', stringvalue, seconds)) except Exception as e: print("connect error ", str(e)) #写数据 #random_string_generator(startup_node, ranlong, size, chars, write=1) #读数据 random_string_generator(startup_node, write=0)