python的redis客户端工具redis-py-cluster可以实现对redis的操作。
1、连接redis单点
import redis
r = redis.Redis(host=ip,port=port,password=password,decode_responses=True)
r.set(key,value)
r.get(key)
#decode_response指定是否对返回值进行解码,默认为false,返回为字节类型
2、连接redis单点,设置连接池
import redis
def get_connection_redis(host, port,password):
try:
pool = redis.ConnectionPool(host=host, port=port,password=password,decode_responses=True)
c = redis.Redis(connection_pool=pool)
except Exception as e:
return e
return c
conn = get_connection_redis(ip,port,password)
conn.set(key,value)
conn.get(key)
#连接池方式:
#当程序创建数据源实例时,系统会一次性创建多个数据库连接,并把这些数据库连接保存在连接池中,当程序需
#要进行数据库访问时,无需重新新建数据库连接,而是从连接池中取出一个空闲的数据库连接
#可以设置max_connections最大连接数,默认为2的31次方,当连接超出该值时会报错
#pool = redis.ConnectionPool(host=host, port=port,password=password,decode_responses=True,max_connections=numb)
#decode_responses是否对返回值进行解码
3、连接redis cluster
from rediscluster import StrictRedisCluster
startup_nodes=[
{'host':'192.168.1.2','port':6378},
{'host':'192.168.1.2','port':6380},
{'host':'192.168.1.2','port':6381},
{'host':'192.168.1.2','port':6382},
{'host':'192.168.1.2','port':6383},
{'host':'192.168.1.2','port':6384},
{'host':'192.168.1.2','port':6385}
]
src = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True,password="123456")
nodes = src.cluster_nodes()
print(nodes)
#注意连接设置密码的redis集群时,密码不能设置在startup_nodes中,需要在StrictRedisCluster中指定密码