kmgilbert100 kmgilbert100 - 1 year ago 146
Node.js Question

Redis / Node wait for key to exist

Is it possible to wait for a key to exist in Redis? Have a Engine running in the background that handles the heavy lifting. The idea is to have the rest api send requests to Redis, and the engine read from that list. The rest api would then monitor a specific key which would eventually contain the response to send to the client.

Is this possible? - When I do my own research I keep coming up on BLPOP, however this is for a list and not a specific key in Redis.

Is there a better approach to do this?

Answer Source

You can use the Redis Keyspace Notification feature to achieve the goal.

With this feature, Redis publishes a message to a specific channel when someone create/set a given key. In order to wait for a given key to exist, you only need to subcribe this specific channel, and wait for the notification.

// Enable keyspace notification:
config set notify-keyspace-events g$K
// subscribe the specific channel: __keyspace@<db_num>__:<key_name>
subscribe '__keyspace@0__:key'

When someone set the key, you'll get the following notification:

1) "message"
2) "__keyspace@0__:key"
3) "set"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download