Monday, July 13, 2015

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.

  1. string.Format("{0}:ServiceTypeList", clientConfiguration.Code);
  2.       string.Format("{0}:PropertyViewModelList", clientConfiguration.Code);
  3.       string.Format("{0}-{1}:FaultTypeList", clientConfiguration.Code,
  4.                     serviceType.ServiceTypeID);
  5.       string.Format("{0}-{1}:LocationList", clientConfiguration.Code,
  6.                     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

  1. private static ConnectionMultiplexer _connection;
  2.  
  3. public static IServer GetDataCacheServer()
  4. {
  5.     if (_connection == null || !_connection.IsConnected)
  6.     {
  7.         _connection = ConnectionMultiplexer.Connect(HybridConfig.GetAppSetting("RedisCacheConnectionString"));
  8.     }
  9.  
  10.  
  11.     var endpoints = _connection.GetEndPoints();
  12.     var server = _connection.GetServer(endpoints.First());
  13.     return server;
  14.  
  15. }
  16.  
  17.  
  18. public static IEnumerable<RedisKey> GetAllCacheKeys()
  19. {
  20.     var server = GetDataCacheServer();
  21.  
  22.     var keys = server.Keys();
  23.     return keys;
  24. }

2. Create Remove method

  1. public static void Remove(string key)
  2.         {
  3.            
  4.  
  5.             try
  6.             {
  7.                 key = string.Format("{0}_{1}_{2}", key, HybridConfig.GetAppSetting("ApplicationUrl"), HybridConfig.GetAppSetting("ApplicationVersion"));
  8.                 var database = GetDataCache();
  9.                 database.KeyDelete(key);
  10.              
  11.                 if (AllKeys.Contains(key))
  12.                 {
  13.                     AllKeys.Remove(key);
  14.                 }
  15.             }
  16.             catch (Exception ex)
  17.             {
  18.                 SqlLogger.Error(typeof(AzureCache), string.Format("Error while trying to remove the key : {0} | Message : {1}", key, ex.Message), ex);
  19.             }
  20.         }

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 !!!

1 comment :

  1. My 0.2 cents.

    1) 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

    ReplyDelete