Redis连接

Python操作Redis连接

linux安装:https://www.redis.com.cn/linux-install-redis.html

windows安装:https://www.redis.com.cn/redis-installation.html

1.Redis连接

import redis

# decode_response=True 指定输出str类型(redis输出的数据类型为bytes)
rdb = redis.Redis(host='localhost', port=6379, db=15, password='xx', decode_response=True)
rdb.set(name='A', value='123', ex=None, px=None, nx=False, xx=False)
a = rdb.get('A')

2. Redis连接池

# 方式一:Redis连接池(官方不推荐)
from redis import ConnectionPool, Redis

# decode_response=True 指定输出str类型(redis输出的数据类型为bytes)
# max_connections=10 指定连接数
pool = ConnectionPool(host='localhost', port=6379, db=15, password='xx', decode_response=True, max_connections=10)
rdb = Redis(connection_pool=pool)
rdb.set('B', '777')
b = rdb.get('B')
# 方式二:StrictRedis连接池
from redis import ConnectionPool, StrictRedis

# decode_response=True 指定输出str类型(redis输出的数据类型为bytes)
# max_connections=10 指定连接数
pool = ConnectionPool(host='localhost', port=6379, db=15, password='xx', decode_response=True, max_connections=10)
rdb = StrictRedis(connection_pool=pool)
rdb.set('C', '778')
b = rdb.get('C')

3.Redis管道

redis-python 默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作

pipeline 则支持在连接和断开之间,执行多个操作

from redis import ConnectionPool, StrictRedis
import time

pool = ConnectionPool(host='localhost', port=6379, db=15, password='xx', decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 默认的情况下,管道里执行的命令可以保证执行的原子性
# pipe = r.pipeline(transaction=False) 可以禁用这一特性。
# pipe = r.pipeline(transaction=True)  默认情况
# 集群模式下使用pipeline,在创建pipeline的对象时,需指定
# pipe =conn.pipeline(transaction=False)

pipe = r.pipeline() # 创建一个管道

# pipe.multi() 启动管道的事务块,可通过`execute`结束事务块
pipe.set('name', 'jack')
pipe.set('age', 20)
pipe.sadd('set_name', 'a', 'b')
pipe.execute()
posted @ 2020-09-01 10:25  丶小白吖  阅读(244)  评论(0编辑  收藏  举报