If you add expiration's to entities you are adding into Redis e.g. in ServiceStack.Redis:
redisClient.Set(elementKey, "some cached value", DateTime.Now.AddMinutes(2));
how can you then subscribe to the element's expiration. The desired outcome would be something ala:
redisClient.Subscribe(elementKey, "expire", DoSomethingBasedOnKey)
Actually you can subscribe to expired keys events, but like Matias said it may take some time until Redis will publish the event.
Redis has Keyspace notifications, you can read about it here,
Keyspace notifications allows clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.
Type of events
Keyspace notifications are implemented sending two distinct type of events for every operation affecting the Redis data space. For instance a DEL operation targeting the key named mykey in database 0 will trigger the delivering of two messages, exactly equivalent to the following two PUBLISH commands:
PUBLISH keyspace@0:mykey del
PUBLISH keyevent@0:del mykey
So what you need is to subscribe to the channel that will publish a message on expired command of keyevent(work also when ttl is reached), it prefix will be like so: "keyevent@0:expired"
Timing accuracy wasn't matter at my case so I've implemented it like so using the ServiceStack C# Redis client:
string EXPIRED_KEYS_CHANNEL = "__keyevent@0__:expired";
using (IRedisClient client = redisClient.GetClient())
{
using (var cacheSubscription = client.CreateSubscription())
{
cacheSubscription.OnMessage += (ch, expiredKey) =>
{
FireOnKeyExpired(expiredKey);
};
cacheSubscription.SubscribeToChannels(EXPIRED_KEYS_CHANNEL);
}
}
Update:
Make sure to configure redis.conf to allow key events on expired keys:
notify-keyspace-events Ex
Or on the fly like so(configuration may be lost when instance is restarted)
config set notify-keyspace-events Ex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With