管道示例¶
这个示例快速展示了如何在 redis-py
中使用管道。
检查 Redis 是否正在运行¶
[1]:
import redis
r = redis.Redis(decode_responses=True)
r.ping()
[1]:
True
简单示例¶
创建一个管道实例¶
[2]:
pipe = r.pipeline()
向管道添加命令¶
[3]:
pipe.set("a", "a value")
pipe.set("b", "b value")
pipe.get("a")
[3]:
Pipeline<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>
执行管道¶
[4]:
pipe.execute()
[4]:
[True, True, 'a value']
这三个命令的响应存储在一个列表中。在上述示例中,前两个布尔值表示 set
命令成功执行,列表的最后一个元素是 get("a")
命令的结果。
链式调用(Chained call)¶
通过链式操作,可以在一行代码中获得与上述相同的结果。
[5]:
pipe = r.pipeline()
pipe.set("a", "a value").set("b", "b value").get("a").execute()
[5]:
[True, True, 'a value']
性能比较(Performance comparison)¶
使用管道可以提高性能,欲了解更多信息,请参见 Redis 文档关于管道的部分。以下是对基本命令和管道命令性能的简单比较测试(我们简单地增加一个值并测量两种方法所花费的时间)。
[6]:
from datetime import datetime
incr_value = 100000
不用管道(Without pipeline)¶
[7]:
r.set("incr_key", "0")
start = datetime.now()
for _ in range(incr_value):
r.incr("incr_key")
res_without_pipeline = r.get("incr_key")
time_without_pipeline = (datetime.now() - start).total_seconds()
[8]:
print("Without pipeline")
print("================")
print("Time taken: ", time_without_pipeline)
print("Increment value: ", res_without_pipeline)
Without pipeline
================
Time taken: 21.759733
Increment value: 100000
使用管道(With pipeline)¶
[9]:
r.set("incr_key", "0")
start = datetime.now()
pipe = r.pipeline()
for _ in range(incr_value):
pipe.incr("incr_key")
pipe.get("incr_key")
res_with_pipeline = pipe.execute()[-1]
time_with_pipeline = (datetime.now() - start).total_seconds()
[10]:
print("With pipeline")
print("=============")
print("Time taken: ", time_with_pipeline)
print("Increment value: ", res_with_pipeline)
With pipeline
=============
Time taken: 2.357863
Increment value: 100000
使用管道可以在更短的时间内获得相同的结果。