Skip to content

Instantly share code, notes, and snippets.

@sayganov
Last active December 22, 2023 00:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sayganov/a57c8290da9539495879cce10669aa2e to your computer and use it in GitHub Desktop.
Save sayganov/a57c8290da9539495879cce10669aa2e to your computer and use it in GitHub Desktop.
Redis keyspace notifications
using StackExchange.Redis;
var configurationOptions = new ConfigurationOptions
{
EndPoints =
{
"localhost:6379"
}
};
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
var subscriber = connectionMultiplexer.GetSubscriber();
await subscriber.SubscribeAsync("__keyspace@0__:*", (channel, type) =>
{
var key = GetKey(channel);
switch (type)
{
case "set":
Console.WriteLine($"Set: {key}");
break;
case "expire":
Console.WriteLine($"Expire: {key}");
break;
case "expired":
Console.WriteLine($"Expired: {key}");
break;
}
});
Console.ReadLine();
await subscriber.UnsubscribeAllAsync();
await connectionMultiplexer.DisposeAsync();
static string GetKey(string channel)
{
var index = channel.IndexOf(':');
if (index >= 0 && index < channel.Length - 1)
{
return channel[(index + 1)..];
}
return channel;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment