Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement "trigger" for redis datastore?

I have a program, which will poll on a certain key from the redis datastore, and do something when the value satisfies a certain condition.

However, I think periodically polling on redis is quite inefficient, I'm wondering if there is a "trigger" mechanism for redis, when the value changes and satisfies the condition, the trigger will be called. The trigger might be a RPC function, or an HTTP msg, or something else, so that I don't need to poll on it any more, just like the difference between poll and interrupt.

Is this possible?

like image 807
ciphor Avatar asked Feb 28 '12 02:02

ciphor


3 Answers

You can use the Pub/Sub feature of Redis. It's exactly what you need given your circumstances as you described.

Essentially, you SUBSCRIBE to a "channel", and the other part of your application writes (PUBLISH) the value being changed to that channel. Your subscriber (consumer, the client that wants to know about the change) will get notified in virtually realtime.

like image 161
Ofer Zelig Avatar answered Sep 17 '22 15:09

Ofer Zelig


If you can use Pub/Sub, that's best. If for some reason that doesn't work, you could also use the (performance-impacting) MONITOR command, which will send you every command the server receives. That's probably not a good idea.

Specifically for lists, you have BLPOP, which will block the connection until a new item is available to pop from a list.

like image 1
menacingly Avatar answered Sep 21 '22 15:09

menacingly


Since Redis 2.8 (released 22 Nov 2013), there is now a feature called Keyspace Notifications which lets clients subscribe to special Pub/Sub channels for keyspace events, which you can use as a trigger on a certain key.

The feature is disabled by default because "while not very sensible the feature uses some CPU power." To enable, send a CONFIG SET command to configure the feature. For example, the following command will enable keyspace events for String commands:

> CONFIG SET notify-keyspace-events K$
OK

Next, use the regular pubsub SUBSCRIBE command to subscribe to the specially-named channel. For example, to listen to keyspace events on the mykey key in DB 0:

> SUBSCRIBE __keyspace@0__:mykey
Reading messages... (press Ctrl-C to quit)

Test out the feature by setting the key's value from another client:

> SET mykey myvalue
OK

You should receive a message in the subscribed client:

1) "message"
2) "__keyspace@0__:mykey"
3) "set"

After receiving the event, you can fetch the updated value and see if it satisfies the condition in your application code.

like image 4
wjordan Avatar answered Sep 18 '22 15:09

wjordan