Last active
December 22, 2023 00:27
-
-
Save sayganov/a57c8290da9539495879cce10669aa2e to your computer and use it in GitHub Desktop.
Redis keyspace notifications
This file contains 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.
Learn more about bidirectional Unicode characters
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