Search code examples
c#cachingazureredisazure-caching

Azure Redis Cache Get and Set Complex Types


I'm creating a POC to see if we can use the azure redis cache for our next project. I had a look at this MSDN documentation http://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/#connect-to-cache.

And have following questions/doubts:

  1. Only way (elegant) to connect to redis is via code below? Is it not possible to do same as Redis Cache where you configure and just works?

ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,ssl=true,password=...");

  1. We need to call above and connect to redis for every Get and Set? If not how can we call only once and re-use?

  2. All I can see is StringGet and StringSet. Is it possible to set the complex .NET Types as well? Example would be good. Below is what I've done in past using dedicate azure cache or ent.Lib cache.

public class CacheManager {

    public void AddToCache(string Id, T value)
    {
        string Key = this.MakeKey(Id);

        if (this.m_Cache.Contains(Key))
        {
            this.m_Cache.Remove(Key);
        }
        ------
        this.m_Cache.Add(Key, value,CacheItemPriority.Normal, null, expireTime);
    }         }

Solution

  • You can have a single instance of the ConnectionMultiplexer and use it for your entire application. You do not need to create one for each Get/Set call. You can find an example http://azure.microsoft.com/blog/2014/06/05/mvc-movie-app-with-azure-redis-cache-in-15-minutes/. I am copying the relevant code below

      private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
          {
    
          var config = new ConfigurationOptions();
                config.EndPoints.Add(cachename);
                config.Password = password;
                config.Ssl = true;
                config.SyncTimeout = 150;
    
               return ConnectionMultiplexer.Connect(config);
          });
    

    You can store objects in the Cache as well. The same link I mentioned above shows how can you serialize .NET Objects into the Cache.