Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redis python psubscribe to event with callback, without calling .listen()

I'm trying to subscribe to keyspace event in redis using python. I hope to NOT use the for-loop with .listen() after calling .psubscribe(). Is this possible?

I have enabled all keyspace events with 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
like image 924
Keven Wang Avatar asked Mar 12 '19 01:03

Keven Wang


1 Answers

Using redis module threads

A good alternative would be using redis.client.PubSub.run_in_thread method.


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)

There is a good step-by-step explanation here.

Using asyncio (aioredis)

This code can be updated for an asyncio version, using aioredis Pub/Sub support. Here is the doc and an example.

like image 187
Andre Pastore Avatar answered Nov 12 '22 22:11

Andre Pastore