python连接redis,redis集群
Posted 乐乐熊小妹
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python连接redis,redis集群相关的知识,希望对你有一定的参考价值。
python连接redis:
import redis r = redis.Redis(host=\'192.168.50.181\',port=6002) r.set(\'user_phone_14900000001\',\'888888\') r.get(\'user_phone_14900000001\')
上面代码如果只执行一条数据是正常的,如果要用for循环批量更改数据连接redis集群,会报错redis.exceptions.ResponseError()
解决方案如下:
python连接redis集群:
from rediscluster import StrictRedisCluster list = [ \'14900000001\', \'14900000002\', \'14900000003\', \'14900000004\', \'14900000005\', \'14900000006\', \'14900000007\', \'14900000008\', \'14900000009\', \'14900000010\' ] def redis_cluster(list): redis_nodes = [ {\'host\':\'192.168.50.39\',\'port\':6002}, {\'host\':\'192.168.50.181\',\'port\': 6002}, ] try: redisconn = StrictRedisCluster(startup_nodes=redis_nodes) except: print(\'error\') for i in range(0,len(list)): redisconn.set(\'user_phone_\'+list[i],\'888888\') print(redisconn.get(\'user_phone_\'+list[i])) redis_cluster(list)
打印结果如下:
b\'888888\'
b\'888888\'
b\'888888\'
b\'888888\'
b\'888888\'
b\'888888\'
b\'888888\'
b\'888888\'
b\'888888\'
b\'888888\'
def redis_cluster(): redis_nodes = [ {\'host\':\'192.168.50.39\',\'port\':6002}, {\'host\':\'192.168.50.181\',\'port\': 6002}, ] try: redisconn = StrictRedisCluster(startup_nodes=redis_nodes) except: print(\'error\') for i in range(14900000011,14900000021): redisconn.set(\'user_phone_\'+str(i),\'888888\') print(redisconn.get(\'user_phone_\'+str(i))) redis_cluster()
以上是关于python连接redis,redis集群的主要内容,如果未能解决你的问题,请参考以下文章