redis python p订阅带有回调的事件,而无需调用.listen()

时间:2019-03-12 01:13:38

标签: python redis redis-py

我正在尝试使用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

1 个答案:

答案 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