gpt4 book ai didi

python - 如何在多线程程序中更高效地使用redis-py?

转载 作者:可可西里 更新时间:2023-11-01 11:21:58 29 4
gpt4 key购买 nike

我有两个问题。

  1. 创建一个全局实例并在每个线程中重复使用或在每个线程中创建一个新实例?

  2. 使用

    pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
    r = redis.Redis(connection_pool=pool)

    r = redis.StrictRedis(host='localhost', port=6379, db=0)

    关于 ConnectionPool 的文档说:您可以选择这样做以实现客户端分片或更好地控制连接的管理方式。但我不明白什么是 客户端分享引用.

更新
如果使用 ConnectionPool,下面哪种方式是正确的?
答:

pool = redis.ConnectionPool(host='localhost', port=6379, db=0)

class DownloadThread(threading.Thread):
def __init__(self,pool):
threading.Thread.__init__(self)
self.r = redis.Redis(connection_pool=pool)
def run(self):
while True:
self.r .....

乙:

pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.Redis(connection_pool=pool)

class DownloadThread(threading.Thread):
def __init__(self,r):
threading.Thread.__init__(self)
self.r = r
def run(self):
while True:
self.r .....

最佳答案

Redis 现在是线程安全的:https://github.com/andymccurdy/redis-py

Redis client instances can safely be shared between threads. Internally, connection instances are only retrieved from the connection pool during command execution, and returned to the pool directly after. Command execution never modifies state on the client instance.

连接池由Redis()的每个实例自动创建

关于python - 如何在多线程程序中更高效地使用redis-py?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23356472/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com