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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With