node.jsredisttl

How to receive Redis expire events with node?


I want to listen the expire events from Redis. I've configured on my redis.conf the notify-keyspace-events "AKE" and this is my code on node:

const redis = require('redis');
const client = redis.createClient();
const subscriber = redis.createClient();
const KEY_EXPIRING_TIME = 10; // seconds

client.setex('myKey', KEY_EXPIRING_TIME, 'myValue');

subscriber.on('message', function(channel, msg) {
  console.log( `On ${channel} received ${msg} event`);
});

subscriber.subscribe('myKey', function (err) {
  console.log('subscribed!');
});

What I hope is to see in 10 seconds that the event is triggered. The setex command works correctly, in 10 seconds the key is not in the database, I have the problem when I try to capture the event.

What am I doing wrong?


Solution

  • no need for setInterval / setTimeout or additional libraries

    you can get every expired key from below the code.

    import { createClient } from "redis";
    
    const pub=createClient({ url: process.env.REDIS_URL });
    pub.connect();
    pub.configSet("notify-keyspace-events", "Ex");
    
    const sub=pub.duplicate();
    sub.connect();
    
    sub.subscribe("__keyevent@0__:expired", (key) => {
        console.log("key=> ", key)
    })
    

    Note: this code is tested with redis@4.0.0