Friday, June 15, 2012

Redis as OutputCacheProvider in ASP.NET

Basic implementation of Redis as OutputCacheProvider:
public class RedisBRCacheProvider : OutputCacheProvider
 {
  private readonly RedisClient redisClient;
  private Object cacheLock = new Object();


  public RedisBRCacheProvider()
  {
   redisClient = new RedisClient("locahost");
  }

  public override object Add(string key, object entry, System.DateTime utcExpiry)
  {
   Debug.WriteLine("Cache.Add(" + key + ", " + entry + ", " + utcExpiry + ")");
   lock (cacheLock)
   {
    var cacheItem = redisClient.Get(key);
    if (cacheItem != null)
    {
     if (cacheItem.Expiration.ToUniversalTime() <= DateTime.UtcNow)
     {
      redisClient.Remove(key);
      this.Set(key, entry, utcExpiry);
     }
     else
      return SerializationHelper.Deserialize(cacheItem.Data);
    }

    this.Set(key, entry, utcExpiry);
   }
   return entry;
  }

  public override object Get(string key)
  {
   lock (cacheLock)
   {
    //If Exists() the int value will be 1, otherwise 0
    if (redisClient.Exists(key) > 0)
    {
     var getKeyData = redisClient.Get(key);
     if (getKeyData != null)
      return SerializationHelper.Deserialize(getKeyData);
    }
    return null;
   }
  }

  public override void Remove(string key)
  {
   lock (cacheLock)
   {
    var cacheItem = redisClient.Get(key);
    redisClient.Delete(cacheItem);
    redisClient.Save();
   }
  }

  public override void Set(string key, object entry, System.DateTime utcExpiry)
  {
   lock (cacheLock)
   {
    var cacheItem = new CacheItem();
    cacheItem.Key = key;
    cacheItem.Data = SerializationHelper.Serialize(entry);
    cacheItem.Expiration = utcExpiry;
    this.Save(cacheItem, key);
   }
  }

  public void Save(CacheItem item, string key)
  {
   lock (cacheLock)
   {
    redisClient.Set(key, item.Data);
    redisClient.Save();
   }
  }
Add this to your web.config