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.

Answer from Marc Gravell on Stack Overflow
🌐
StackExchange.Redis
stackexchange.github.io › StackExchange.Redis › KeyspaceNotifications.html
Redis Keyspace Notifications | StackExchange.Redis
Redis keyspace notifications let you monitor operations happening on your Redis keys in real-time. StackExchange.Redis provides a strongly-typed API for subscribing to and consuming these events.
Top answer
1 of 2
26

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.

2 of 2
2

Just to extend what the selected answer already describes:

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

    subscriber.Subscribe($"__keyspace@0__:{channel}", (channel, value) =>
        {
          // Do whatever channel specific handling you need to do here, in my case I used exact Key name that I wanted expiration event for.  
        }
    );
}

Another important thing, I had to subscribe KEx (CONFIG SET notify-keyspace-events KEx ) to get channel based updates for expiration notifications.

Discussions

caching - Redis keyspace notifications with StackExchange.Redis For Delete operation - Stack Overflow
I've been searching to find out how to perform a subscription to key space notifications on Redis using ServiceStack.Redis library for removal of Key. Checking available tests on the git-hub and o... More on stackoverflow.com
🌐 stackoverflow.com
channelPrefix disables Keyspace Notifications
Using a connectionString with a channelPrefix options seems to disable all Keyspace Notifications. As far as I can tell, all Pub/Sub Messages are checked against the prefix - if any is configured (... More on github.com
🌐 github.com
1
July 5, 2016
stackexchange.redis - Redis Keyspace Notifications with flushdb - Stack Overflow
The keyspace notifications have been essential for a recent web api I've been developing. We have redis setup in azure. The api mostly works, we use notifications to figure out if data on memory c... More on stackoverflow.com
🌐 stackoverflow.com
c# - How to filter Redis Keyspace notifications - Stack Overflow
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 ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › JonCole › 0d6205b4771e5c803bc1e085517484a2
Redis Keyspace Notification Example · GitHub
Redis Keyspace Notification Example · Raw · RedisKeyspaceNotificationsExample.cs · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Microsoft Community Hub
techcommunity.microsoft.com › microsoft community hub › communities › products › azure › azure paas blog
Redis Keyspace Events Notifications | Microsoft Community Hub
January 15, 2021 - Removing all the text leaving a empty box and saving, will disable the Redis Keyspace notifications. ... In this case we will use the psubscribe command using Redis Console available in Azure Portal to subscribe both types of events in any database, for all events and all keys: ... Using Stackexchange.Redis client library to subscribe notifications, we may need to develop some app and use this Class.
🌐
Blogger
hrcode11.blogspot.com › 2013 › 03 › c-redis-keyspace-notifications-with.html
c# - Redis keyspace notifications with StackExchange.Redis -
November 18, 2017 - 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") { // stuff if item added hypothethical "users" set in redis } } ); }
🌐
GitHub
github.com › StackExchange › StackExchange.Redis › issues › 439
channelPrefix disables Keyspace Notifications · Issue #439 · StackExchange/StackExchange.Redis
July 5, 2016 - Using a connectionString with a channelPrefix options seems to disable all Keyspace Notifications. As far as I can tell, all Pub/Sub Messages are checked against the prefix - if any is configured (RawResult.cs#L80). Since the Keyspace an...
Author   zivillian
🌐
DEV Community
dev.to › sayganov › redis-keyspace-notifications-with-a-c-example-2ahp
Redis keyspace notifications with a C# example - DEV Community
April 25, 2023 - In this blog post, we will explore Redis keyspace notifications and demonstrate how to use them in a C# application. We will cover the different types of events that can trigger notifications, how to configure Redis to send notifications, and how to receive and process notifications in a C# application using the StackExchange.Redis library.
Find elsewhere
🌐
DEV Community
dev.to › serhatayata › redis-keyspace-notifications-with-docker-4o90
Redis Keyspace Notifications with Docker - DEV Community
December 16, 2023 - The 'notify-keyspace-events' we set above is initially disabled by default. To activate it, we can use the characters shown in the image above. With these characters, we can decide which events to log. The 'KEA' used above activates all of them. Now, we can implement it within the .NET Console App as follows: After creating our application, we can install the StackExchange.Redis ...
🌐
Redis
redis.io › docs › latest › develop › pubsub › keyspace-notifications
Redis keyspace notifications | Docs
5 days ago - Setting the parameter to the empty string disables notifications. In order to enable the feature a non-empty string is used, composed of multiple characters, where every character has a special meaning according to the following table: K Keyspace events, published with __keyspace@<db>__ prefix.
🌐
GitHub
github.com › redis-developer › keyspace-notifications-node-redis
GitHub - redis-developer/keyspace-notifications-node-redis: Keyspace Notifications demo with Node Redis 4 · GitHub
We'll use a Redis Sorted Set to keep track of the high scores. We only need a single key for this, and we'll call that scoreboard. What we want to do is use keyspace notifications to track updates to those tokens:username Set keys for us.
Starred by 7 users
Forked by 2 users
Languages   Python 70.2% | JavaScript 29.8%
🌐
GitHub
github.com › redis › redis-doc › blob › master › docs › manual › keyspace-notifications.md
redis-doc/docs/manual/keyspace-notifications.md at master · redis/redis-doc
Every node of a Redis cluster generates events about its own subset of the keyspace as described above. However, unlike regular Pub/Sub communication in a cluster, events' notifications are not broadcasted to all nodes. Put differently, keyspace ...
Author   redis
Top answer
1 of 2
2

From Redis Keyspace Notifications

Keyspace notifications allow clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.

Examples of events that can be received are:

All the commands affecting a given key.
All the keys receiving an LPUSH operation.
All the keys expiring in the database 0.

Events are delivered using the normal Pub/Sub layer of Redis, so clients implementing Pub/Sub are able to use this feature without modifications.

So, if you need just pub/sub, there is no need of extra configuration regarding Keyspace Notifications

2 of 2
0

key-space-notifications and pub/sub are 2 different concepts.

PUB/SUB: It's usual method publishing data to a channel and other clients can subscribe to the same channel by it's name. published messages are characterised into channels, without knowledge of what (if any) subscribers there may be.

This is enabled by default. messages are not persisted here, and once delivered/lost, messages cannot be retrieved.

key-space-notifications: This also a way of subscribing to Pub/Sub channels in order to receive events by the clients.

This we need to enable manually as this consumes little more CPU. Use below code to enable this

redisClient.configSet("notify-keyspace-events", "Ex");

we can subscribe to 2 different channels

  1. Key-space channel: receives the name of the event as message.
  2. Key-event channel: receives the name of the key as message.

example: To subscribe to key expired events, use the below code

export const subscribeForExpiry = () => {
  //.: Subscribe to the "notify-keyspace-events" 
  // channel used for expired type events
  client.configSet("notify-keyspace-events", "Ex");
  const sub = client.duplicate();
  sub.connect();

  sub.subscribe(
    `__keyevent@${process.env.REDIS_DATABASE_INDEX}__:expired`,
    (key) => {
      console.log("key=> ", key);
      // do something with key, can't retrieve value here
    }
  );
};
🌐
Redis
redis.io › docs › latest › develop › pubsub › keyspace-notifications › index.html.md
Redis
For instance a [`DEL`]() operation ... channel listens only to `del` operation events on the key `mykey` The first kind of event, with `keyspace` prefix in the channel is called a **Key-space notification**, while the second, with the `keyevent` prefix, is called a **Key-event ...
🌐
GitHub
github.com › StackExchange › StackExchange.Redis › issues › 789
Cluster pub/sub: keyspace notification issues · Issue #789 · StackExchange/StackExchange.Redis
March 1, 2018 - Hoping this is just something I'm doing wrong, but I have a cluster with two master-slaves. I've found I'm unable to use a pattern subscription because it just subscribes to one master's notifications (and redis doesn't broadcast notifications across cluster by design).
Author   klords
🌐
GitHub
github.com › StackExchange › StackExchange.Redis › issues › 993
Keyspace notifications not working on linux (.netcore) · Issue #993 · StackExchange/StackExchange.Redis
October 31, 2018 - Simple app using azure redis. Works fine on windows and windows containers. Running on linux or linux containers you never receive keyspace notifications. var connection = StackExchange.Redis.ConnectionMultiplexer.Connect(Configuration["RedisEndpoint"]); int db = int.Parse(Configuration["RedisDB"]); StackExchange.Redis.IDatabase cache = connection.GetDatabase(db); var subscriber = connection.GetSubscriber(); string notificationChannel = "__keyspace@" + db + "__:*"; subscriber.Subscribe(notificationChannel, (channel, notificationType) => { });
🌐
GitHub
github.com › StackExchange › StackExchange.Redis › pull › 1536 › files
Adding support for cluster keyspace notifications to subscriber by ercangorgulu · Pull Request #1536 · StackExchange/StackExchange.Redis
Adding support for cluster keyspace notifications to subscriber by allowing subscription to multiple nodes Refactored code for previous pull request based on new changes #813 Fixes: #789
Author   StackExchange
🌐
Redis
redis.io › docs › latest › operate › oss_and_stack › stack-with-enterprise › deprecated-features › triggers-and-functions › concepts › triggers › keyspace_triggers
Keyspace triggers | Docs
5 days ago - What just happened? name_jerry was incremented twice while name_tom was not incremented at all. This happened because, in case of a multi/exec or Lua function, the notifications are fired at the end of the transaction, so all the clients will receive notifications of the last value written, which is jerry.