Kev*_*ang 9 python redis redis-py
我正在尝试使用 python 在 redis 中订阅 keyspace 事件。我希望.listen()在调用之后不要使用 for 循环.psubscribe()。这可能吗?
我已经启用了所有键空间事件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
Run Code Online (Sandbox Code Playgroud)
And*_*ore 12
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)
Run Code Online (Sandbox Code Playgroud)
这里有一个很好的分步解释。
asyncio(aioredis)asyncio可以使用Pub/Sub 支持来更新此代码的版本aioredis。这是文档和示例。
| 归档时间: |
|
| 查看次数: |
3455 次 |
| 最近记录: |