Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis keyspace notifications with StackExchange.Redis

I've looking around and I'm unable to find how to perform a subscription to keyspace notifications on Redis using StackExchange.Redis library.

Checking available tests I've found pubsub using channels, but this is more to work like a service bus/queueing rather than subscribing to specific Redis key events.

Is it possible to take advantage of this Redis feature using StackExchange.Redis?

like image 936
Matías Fidemraizer Avatar asked Apr 20 '14 09:04

Matías Fidemraizer


1 Answers

The regular subscriber API should work fine - there is no assumption on use-cases, and this should work fine.

However, I do kinda agree that this is inbuilt functionality that could perhaps benefit from helper methods on the API, and perhaps a different delegate signature - to encapsulate the syntax of the keyapace notifications so that people don't need to duplicate it. For that: I suggest you log an issue so that it doesn't get forgotten.

Simple sample of how to subscribe to a keyspace event

First of all, it's important to check that Redis keyspace events are enabled. For example, events should be enabled on keys of type Set. This can be done using CONFIG SET command:

CONFIG SET notify-keyspace-events KEs

Once keyspace events are enabled, it's just about subscribing to the pub-sub channel:

using (ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("localhost"))
{
    IDatabase db = connection.GetDatabase();
    ISubscriber subscriber = connection.GetSubscriber();

    subscriber.Subscribe("__keyspace@0__:*", (channel, value) =>
        {
            if ((string)channel == "__keyspace@0__:users" && (string)value == "sadd")
            {
                // Do stuff if some item is added to a hypothethical "users" set in Redis
            }
        }
    );
}

Learn more about keyspace events here.

like image 162
Marc Gravell Avatar answered Oct 06 '22 00:10

Marc Gravell