python连接redis

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中指定密码

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值