ThatAwesomeCoder ThatAwesomeCoder - 6 months ago 56
C# Question

Clear StackExchange.Redis Cache with configurable expiry

I want to know if there is a way to clear / flush the entire cache from my c# service after a specified expiry date. How can I achieve this in c#?

C#

// library
using StackExchange.Redis;

public class RedisCacheService
{
// Fields
ConnectionMultiplexer _Redis = null;
IDatabase _RedisDB = null;

// ctor
public RedisCacheService(String redisConnectionString) // , DateTime ExpiryDate ? - Extracted from config
{
try
{
if (String.IsNullOrEmpty(redisConnectionString))
{
throw new Exception("The 'redisConnectionString' parameter is unassigned");
}

this._Redis = ConnectionMultiplexer.Connect(redisConString);

if (_Redis == null)
{
throw new Exception("_Redis object not initialized");
}

this._RedisDB = _Redis.GetDatabase();

// I need to set some sort of expiry config here in the constructor.

// The redisConnectionString is passed through when an instance of this class is created in the host startup and
// the redisConnectionString is extracted from the config.
}
catch (Exception e)
{
throw new Exception(e);
}
}
}


I saw a similar solution where I can pass in an expiry when I actually populate the cache with the objects but I rather want a global cache clear solution.

Any help or suggestions would be appreciated.

Answer Source

You could add a fake key to redis, like _waitforit, with a TTL set. Then you wait for it to expire. In the meantime, you subscribe to key space events for expired keys. The moment your _waitforit key expires, you flush the database.

The only downside of those events is that you have to explicitly enable it on the Redis server. Can be done via configuration or command line though. You'd need CONFIG SET notify-keyspace-events Exe I think

On a site note:

You could use CacheManager to do most of the job for you, if you don't want to code all that yourself.

It has build in expiration configurations, and you can listen to all those events.

You would be able to subscribe to a normal C# event onRemoveByHandle which gets triggered via key space events (if everything is configured properly), too.