redis里的“流水线”pipeline/pool

情到浓时终转凉″ 提交于 2020-02-08 04:38:33

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()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!