我正在尝试使用python订阅redis中的keyspace事件。我希望在调用.listen()
之后不要在.psubscribe()
中使用for循环。这可能吗?
我已使用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
答案 0 :(得分:0)
一个不错的选择是使用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。