pipeline 流水线
定义:批量执行redis命令,减少通信io,提高执行效率
注意:此为客户端技术,而不是服务端技术
示例
import redis
# 创建连接池并连接到redis
pool = redis.ConnectionPool(host = '127.0.0.1',db=0,port=6379)
r = redis.Redis(connection_pool=pool)
pipe = r.pipeline()
pipe.set('fans',50)
pipe.incr('fans')
pipe.incrby('fans',100)
pipe.execute()
性能对比
# 创建连接池并连接到redis
pool = redis.ConnectionPool(host = '127.0.0.1',db=0,port=6379)
r = redis.Redis(connection_pool=pool)
def withpipeline(r):
p = r.pipeline()
for i in range(1000):
key = 'test1' + str(i)
value = i+1
p.set(key, value)
p.execute()
def withoutpipeline(r):
for i in range(1000):
key = 'test2' + str(i)
value = i+1
r.set(key, value)
if __name__ == '__main__':
t1 = time.time()
# time is: 0.07772541046142578
# withpipeline(r)
# time is: 0.2035658359527588
withoutpipeline(r)
t2 = time.time()
print('time is:', t2-t1)
可见,pipeline可以大幅提高redis的效率
python 操作 redis事务
with r.pipeline(transaction=true) as pipe
pipe.multi()
pipe.incr("books")
pipe.incr("books")
values = pipe.execute()
来源:CSDN
作者:liu*star
链接:https://blog.csdn.net/liuxingxing_star/article/details/104216187