Redis Python подписаться на событие с обратным вызовом, без вызова .listen () - PullRequest
3 голосов
/ 12 марта 2019

Я пытаюсь подписаться на событие пространства ключей в redis, используя python.Я надеюсь НЕ использовать цикл for с .listen() после вызова .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

1 Ответ

0 голосов
/ 04 июля 2019

Хорошей альтернативой будет использование метода 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)

Здесь есть хорошее пошаговое объяснение здесь .

...