Python 使用 Redis单机版本、集群版本操作

转载:https://blog.csdn.net/baidu_27032161/article/details/101295587

转载:https://blog.csdn.net/zzchances/article/details/116223555

Python 操作 Redis单机版

# redis 安装
pip install redis

Python Redis模块常见的 几个类:
Redis模块
Redis
StrictRedis
ConnectionPool

# redis源码
from redis.client import Redis, StrictRedis
from redis.connection import (
BlockingConnectionPool,
ConnectionPool,
Connection,
SSLConnection,
UnixDomainSocketConnection
)

Redis类

#使用redis类操作 redis
def op_redis():
r = redis.Redis(host='192.168.1.21', port=6379, password='test', db=0)
r.set('foo', 'bar')
t = str(r.get('foo'), encoding='utf-8')
print(t)

不推荐使用:redis 是StrictRedis 的子类,redis用于向后兼容旧版本的redis-py,redis类中部分操作与redis-cli不一致,部分操作属性顺序相反,如下:

StrictRedis 类

#使用StrictRedis 类操作 redis
def op_redis_strictRedis():
r = redis.StrictRedis(host='192.168.1.21', port=6379, password='test', db=0)
r.set('foo1', 'bar')
t = str(r.get('foo'), encoding='utf-8')
print(t)

推荐使用: StrictRedis用于实现大部分官方的命令,并使用官方的语法和命令(比如,SET命令对应与StrictRedis.set方法)

redis的对于有些编码入库的问题,redis的连接附加的参数里面,默认编码是utf-8,但是如果你非要用GBK那就需要指明你的chardet和decode_responses为True

ConnectionPool 类

redis-py 通过ConnectionPool类 管理连接池,避免每次建立、释放连接的开销

def op_redis_pool():
pool = redis.ConnectionPool(host='192.168.1.20', port=6379, password='test', db=0)
r = redis.Redis(connection_pool=pool)
r.set('foo1', 'bar')
t = str(r.get('foo'), encoding='utf-8')
print(t)

Python 操作 Redis集群版

通过 redis-py-cluster 模块的 StrictRedisCluster类来操作redis集群版

安装需要的库
# 安装redis-py-cluster过程中,会默认安装一个redis,
# 需要卸载该redis 安装指定版本的redis,以免出现兼容问题
pip install redis-py-cluster==1.3.4
pip install redis==2.10.6

使用
from rediscluster import StrictRedisCluster
def op_redis_cluster():
nodes = [{'host': '192.168.1.10', 'port': '6001'}, {'host': '192.168.1.10', 'port': '6002'}]
r = StrictRedisCluster(startup_nodes=nodes, password='yeemiao2018')
r.set('foo1', 'bar')
t = str(r.get('foo'), encoding='utf-8')
print(t)

关于redis客户端连接超时时间:

为了让Redis主动清理长时间空闲的客户端连接,回收资源,您可以设置timeout参数来限制客户端连接的空闲时间。

不设置超时时间会导致连接长时间占用,可能报错:could not get a resource from the pool

前提条件
实例为Redis 4.0或以上版本的标准版云数据库Redis实例。

说明 集群版或读写分离版Redis实例不支持自定义timeout参数。

Redis的客户端超时机制
在业务场景中,一般会由Redis客户端进行连接资源管理,例如分配连接、监控连接状态、回收连接池资源等。默认设置下,Redis不会主动断开连接,即使这个客户端已经空闲了很长时间。但在业务核心应用中,建议配置timeout参数以使Redis具有主动回收资源的能力。否则,如果客户端出现异常,连接池资源得不到及时回收,可能因空闲连接占满连接池导致服务崩溃。核心应用出现这样的问题可能引发整个业务的混乱,后果严重。

timeout参数值的单位为秒(s),取值范围为0~100000。默认值为0,表示无限制。在实际运行中,为了提高性能,Redis不一定会精确地按照timeout的值规定的时间来断开符合条件的空闲连接,例如设置timeout为10s,但空闲连接可能在12s后,服务器中新增很多连接时才会被断开。如需降低这个延迟,可适当增大hz参数的值,提高负责断开超时连接的Redis定时任务的运行频率。

设置方法:可以通过redis配置文件redisXXX.conf设置timeout 30,也可通过redis命令控制台:CONFIG SET timeout 30



原文地址:https://www.cnblogs.com/to-here/p/15481117.html