Search code examples
redislistener

Listen for changes in redis list


I want to write a function that constantly listens for changes in a redis list (usually when elements are pushed to the list) and pops its elements whenever the list is not empty. Then it will execute a function on the popped elements. How should I implement this?


Solution

  • You can use notify-keyspace-events for that

    example with Node.js but the idea is similar for other languages.

    const Redis = require('ioredis')
    const redis = new Redis()
    
    ;(async function () {
        redis.on('ready', () => {
            console.log('ready');
    
            redis.config('set', 'notify-keyspace-events', 'KEl')
            // KEl => see https://redis.io/topics/notifications to understand the configuration
            // l is meant we are interested in list event
    
            redis.psubscribe(['__key*__:*'])
    
            redis.on('pmessage', function(pattern, channel, message) {
                console.log('got %s', message);
            });
        })
    })()
    

    The complete list for configuration of notify-keyspace-events is here

    K     Keyspace events, published with __keyspace@<db>__ prefix.
    E     Keyevent events, published with __keyevent@<db>__ prefix.
    g     Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
    $     String commands
    l     List commands
    s     Set commands
    h     Hash commands
    z     Sorted set commands
    t     Stream commands
    d     Module key type events
    x     Expired events (events generated every time a key expires)
    e     Evicted events (events generated when a key is evicted for maxmemory)
    m     Key miss events (events generated when a key that doesn't exist is accessed)
    n     New key events (Note: not included in the 'A' class)
    A     Alias for "g$lshztxed", so that the "AKE" string means all the events except "m" and "n".