gpt4 book ai didi

python - redis python psubscribe 事件回调,不调用.listen()

转载 作者:IT王子 更新时间:2023-10-29 06:02:39 24 4
gpt4 key购买 nike

我正在尝试使用 python 订阅 redis 中的键空间事件。我希望在调用 .psubscribe() 后不要将 for 循环与 .listen() 一起使用。这可能吗?

我已使用 KEA 启用所有键空间事件。

def subscribe(self, key, handler):

# this function never gets called, if I don't add the for-loop with listen() below
def event_handler(msg):
print('Handler', msg)

redis_server = StrictRedis(host='localhost', port=6379, db=0)
pubsub = redis_server.pubsub()
subscribe_key = '*'
pubsub.psubscribe(**{subscribe_key: event_handler})

# without the following for-loop with listen, the callback never fires. I hope to get rid of this.
for item in pubsub.listen():
pass

最佳答案

使用redis模块线程

一个好的替代方法是使用 redis.client.PubSub.run_in_thread方法。


def subscribe(self, key, handler):
def event_handler(msg):
print('Handler', msg)

redis_server = StrictRedis(host='localhost', port=6379, db=0)
pubsub = redis_server.pubsub()
subscribe_key = '*'
pubsub.psubscribe(**{subscribe_key: event_handler})

pubsub.run_in_thread(sleep_time=.01)

有很好的分步说明here .

使用asyncio (aioredis)

此代码可以更新为 asyncio 版本,使用 aioredis Pub/Sub 支持。 Here是文档和示例。

关于python - redis python psubscribe 事件回调,不调用.listen(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55112705/

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