Search code examples
c#stackexchange.redisazure-redis-cache

How to filter Redis Keyspace notifications


I am trying to figure out how to properly use the key-event notification system in Redis using Azure Cache for Redis and the StackExchange.Redis package.

Following the documentation from different places, I have been able to get notifications with a setup like this:

var configurationOptions = ConfigurationOptions.Parse(<connection_string>);
_connectionMultiplexer = ConnectionMultiplexer.Connect(configurationOptions);
...
var subscriber = _connectionMultiplexer.GetSubscriber();

subscriber.Subscribe("__keyevent@0__:set", (_, key) =>
{
    _logger.LogWarning("Received '{CacheKey}'", key);            
});

Running the code above and after having configured Redis with the option Eg$ for notifications, I do receive a notification every time a key is written in the cache or deleted from the cache.

I would like to get notifications for certain keys only. For instance, I would like to be able to only receive notifications for keys that start with the characters 'my.key'.

Initial Approach

The naive approach would be something like this.

subscriber.Subscribe("__keyevent@0__:set", (_, key) =>
{
   if(!key.StartsWith("my.key"))
     return;
   _logger.LogWarning("Received '{CacheKey}'", key);            
});

It works but it put the burden on the clients to do the filtering which may not be optimal, especially considering that the (rather expensive) Redis instance is shared across multiple services, which causes my service to receive notifications that are not of interest.

Question

I tried something like the following but it does not seem to work:

"__keyevent@0__:set my.key*"

Is there a way to specify a filter to get certain notifications from Redis?


Solution

  • The correct command that allows me to do the filtering is keyspace.

    With the configuration AKE and the following code, I can get the notifications only for the keys my service is interested in:

    subscriber.Subscribe("__keyspace@0__:my.key*", (_, key) =>
    {
       _logger.LogWarning("Received '{CacheKey}'", key);            
    });