Redis 获取 3000 个 keyhash 的值大约需要 10 秒(python 3.5)

kri*_*nya 3 python performance redis

我是 REDIS 世界的新手。我正在尝试从 REDIS 获取 3000 个键的值。每个哈希有 6 个我想要获取的值。我使用 Python 3.5 一次连接到 REDIS,然后循环遍历我的密钥哈希以从 REDIS 获取它们各自的值。但是,目前获取这 3000 行的值大约需要 10 秒。我使用下面的代码从 REDIS 获取数据。你能帮我加快获取速度吗?有没有办法一次发送所有键并获取与它们相关的值?我为此使用 python 3.5。

redis_pool = redis.ConnectionPool(host='XYZ',
                                  port='XY',
                                  db='X')
r = redis.Redis(connection_pool=red_pool)

field1 = r.hmget(primary_key, "Field1")
Run Code Online (Sandbox Code Playgroud)

Gua*_*Zuo 6

您可以尝试使用管道来加快查询速度。

r = redis.Redis(connection_pool=red_pool)
pipe = r.pipeline()
for key in keys_list: 
    pipe.hget(key, "field1")
results = pipe.execute()
Run Code Online (Sandbox Code Playgroud)

results将是每个 hget 回复的列表。您可以参考redis-py的 readme 的 pipeline 部分来了解有关如何在 python redis 客户端中使用 pipeline 的更多信息。