Clear Azure Cache : Get All keys in Azure Redis cache
Recently I got a requirement to clear cache value for a given client account. In our systems we have multiple contractors , and we cache some data related to that contractor account. Cache keys are as follows.
- string.Format("{0}:ServiceTypeList", clientConfiguration.Code);
- string.Format("{0}:PropertyViewModelList", clientConfiguration.Code);
- string.Format("{0}-{1}:FaultTypeList", clientConfiguration.Code,
- serviceType.ServiceTypeID);
- string.Format("{0}-{1}:LocationList", clientConfiguration.Code,
- property.PropertyNo);
Here some cache keys are based on Client Configuration code, and some have client configuration and some code too. But when we have to clear the cache for a given client account we have only the Client Configuration code. So we used the following approach.
1. Get all Cache Keys
- private static ConnectionMultiplexer _connection;
- public static IServer GetDataCacheServer()
- {
- if (_connection == null || !_connection.IsConnected)
- {
- _connection = ConnectionMultiplexer.Connect(HybridConfig.GetAppSetting("RedisCacheConnectionString"));
- }
- var endpoints = _connection.GetEndPoints();
- var server = _connection.GetServer(endpoints.First());
- return server;
- }
- public static IEnumerable<RedisKey> GetAllCacheKeys()
- {
- var server = GetDataCacheServer();
- var keys = server.Keys();
- return keys;
- }
2. Create Remove method
- public static void Remove(string key)
- {
- try
- {
- key = string.Format("{0}_{1}_{2}", key, HybridConfig.GetAppSetting("ApplicationUrl"), HybridConfig.GetAppSetting("ApplicationVersion"));
- var database = GetDataCache();
- database.KeyDelete(key);
- if (AllKeys.Contains(key))
- {
- AllKeys.Remove(key);
- }
- }
- catch (Exception ex)
- {
- SqlLogger.Error(typeof(AzureCache), string.Format("Error while trying to remove the key : {0} | Message : {1}", key, ex.Message), ex);
- }
- }
3. Search the client configuration code in it and clear the cache
var keys = AzureCache.GetAllCacheKeys();
string applicationTag = string.Format("_{0}_{1}", HybridConfig.GetAppSetting("ApplicationUrl"),
HybridConfig.GetAppSetting("ApplicationVersion"));
List<string> cacheKeys = (from redisKey in keys
select redisKey.ToString()
into key
where key.Contains(applicationTag) && key.Contains(clientConfiguration.Code)
select key.Replace(applicationTag, string.Empty)).ToList();
if (cacheKeys.Any())
cacheKeys.ForEach(AzureCache.Remove);
Happy Coding !!!
My 0.2 cents.
ReplyDelete1) If normal Session stay on RAM, then In-Role Cache also will be on the RAM. So when you do a VIP swap, normal session goes away and same as In-Role Cache.
2) What if in future you are going to load balance your services, in that case having in-role cache will not work unless you go for Session Affinity. So based on above statements, you can think of Azure Cache service.
NCache in azure treats this differently.
http://www.alachisoft.com/ncache/azure-index.html