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輸出的數(shù)據(jù)類型為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輸出的數(shù)據(jù)類型為bytes)
# max_connections=10 指定連接數(shù)
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輸出的數(shù)據(jù)類型為bytes)
# max_connections=10 指定連接數(shù)
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 默認(rèn)在執(zhí)行每次請求都會創(chuàng)建(連接池申請連接)和斷開(歸還連接池)一次連接操作
pipeline 則支持在連接和斷開之間,執(zhí)行多個操作
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)
# 默認(rèn)的情況下,管道里執(zhí)行的命令可以保證執(zhí)行的原子性
# pipe = r.pipeline(transaction=False) 可以禁用這一特性。
# pipe = r.pipeline(transaction=True) 默認(rèn)情況
# 集群模式下使用pipeline,在創(chuàng)建pipeline的對象時,需指定
# pipe =conn.pipeline(transaction=False)
pipe = r.pipeline() # 創(chuàng)建一個管道
# pipe.multi() 啟動管道的事務(wù)塊,可通過`execute`結(jié)束事務(wù)塊
pipe.set('name', 'jack')
pipe.set('age', 20)
pipe.sadd('set_name', 'a', 'b')
pipe.execute()

浙公網(wǎng)安備 33010602011771號