Sth
Sth

Reputation: 532

Can't get key's value after subscribing for expiration

I have a shallow key, which is supposed to expire, after listening to its expiration, I take the key, generate the key which holds the real value and try to get its value.

Code:

//.: Set the config for "notify-keyspace-events" channel used for expired type events
listener.send_command('config', ['set','notify-keyspace-events','Ex']);

// __keyevent@0__:expired is the channel name to which we need to subscribe, 0 is the default DB
listener.subscribe('__keyevent@0__:expired');
listener.on('message', (chan, msg) => {
  listener.get(`${msg}-details`, redis.print);
});

Getting the error below after running listener.get:

ReplyError: ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context

I need the real key's value.

Upvotes: 1

Views: 1322

Answers (2)

Jorge Santana
Jorge Santana

Reputation: 107

Basically you have to create a another listener to get the value. You cannot get it using the listener as the one you are using to publish and subscribe. Here is a quick article explaining how I solved a similar error: https://blog.stackademic.com/resolving-redis-error-in-node-js-a549308df2d3

Upvotes: 0

LeoMurillo
LeoMurillo

Reputation: 6764

As noted in SUBSCRIBE command:

Once the client enters the subscribed state it is not supposed to issue any other commands, except for additional SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE, PUNSUBSCRIBE, PING and QUIT commands.

The usual pattern is you would have two client connections (you would call redis.createClient() twice). Here is an example: How to receive Redis expire events with node?

Basically, you would have one connection for the expiration events, and one for the other logic you want (getting the key value, etc).

Upvotes: 2

Related Questions