Danilo
Danilo

Reputation: 382

Listen to redis expiration events of specific key names

I have a node.js code that listen to redis key expiration events:

const subscriber = require('redis').createClient(port, host);

subscriber.subscribe('__keyevent@0__:expired');

subscriber.on('message', async (channel, key) => {
    // do somenthing
}

But I want to listen to expiration events of specific key name pattern. Example: I want to listen events when keys like "foo_bar_123" and "foo_bar_456" ("foo_bar_*") expire.

Is there a way to achieve this by changing "__keyevent@0__:expired""?

Thanks.

Upvotes: 1

Views: 2174

Answers (1)

for_stack
for_stack

Reputation: 22906

You can listen to the key-space notification:

config set notify-keyspace-events Kx

Then subscribe with a key pattern:

psubscribe __keyspace@0__:foo_bar_*

When foo_bar_1 expires, you'll get the corresponding message:

1) "pmessage"
2) "__keyspace@0__:foo_bar_*"
3) "__keyspace@0__:foo_bar_1"
4) "expired"

Upvotes: 3

Related Questions