node.jsredisnode-redisredis-cluster

How to access the properties of a deleted or expired key in Redis?


I am using Redis keyspace notifications to access my deleted and expired keys as such :

const Rsub = createClient({
  url: "redis://localhost",
  password: "mypw",
  username: "default",
});
const Rpub = createClient({
  url: "redis://localhost",
  password: "mypw",
  username: "default",
});

 Rpub.connect();
 Rsub.connect();

  Rpub.configSet("notify-keyspace-events", "Ex");

and I can get the expired key through :

Rsub.subscribe('__keyevent@0__:expired', key => console.log(key, 'expired'));

which works well. However the properties of the expried key is more important to me than the key itself. Since key is just a randomly generated ID, I wish to have access to the elements the key contains. Is there any way I can get to find out what was the properties of my deleted key before deletion or afterwards?


Solution

  • In Redis, when a key expires (or is deleted), the original key-value data has already been deleted. This means that once a key expires or is deleted, its value can no longer be retrieved. 

    I think a possible but not perfect solution could be implemented, but it would consume additional memory. When specifying an expiring key, you can also specify a corresponding key that contains the properties or values ​​of the original key. Also, set the expiration time of this new key to be slightly longer than the original key. That way, as soon as the original key expires, you can access this new key to get the information you need and delete it. 

    let key = 'key1'; 
    let data = 'data1'; 
    
    Rpub.set(key, data, 'EX', 10); 
    Rpub.set(key + ':data', JSON.stringify(data), 'EX', 12); 
    
    

    then, get data for this new key on an expired key subscription. 

    Rsub.subscribe('__keyevent@0__:expired', key => {
      Rpub.get(key + ':data', (err, reply) => {
        if (reply) {
          console.log('Data: ', reply);
          Rpub.del(key + ':data'); 
        }
      });
    });