Skip to content

Instantly share code, notes, and snippets.

@ElvisLives
Last active July 26, 2016 17:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElvisLives/41fa3ce32fbd2e0377f45fa350b3fb00 to your computer and use it in GitHub Desktop.
Save ElvisLives/41fa3ce32fbd2e0377f45fa350b3fb00 to your computer and use it in GitHub Desktop.
A working version of IApiOutputCache with Redis (Has some caveats around dependencies.)
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using CachingFramework.Redis;
using WebApi.OutputCache.Core.Cache;
namespace Some.Cool.NameSpace.Goes.Here
{
/// <summary>
/// An implementation of WebApi.OutputCache.Core.Cache.IApiOutputCache that uses Redis as the cache.
/// For more information on Asp.NET Web API CacheOutput see https://github.com/filipw/AspNetWebApi-OutputCache
/// Must use version 0.6.0, all other versions have been broken.
// Requires CachingFramework.Redis at least version 4.7.1
/// </summary>
public class RedisApiOutputCache : IApiOutputCache
{
static RedisApiOutputCache()
{
Context = new Context(ConfigurationManager.ConnectionStrings["RedisCache"].ConnectionString);
}
private static Context Context { get; }
public void RemoveStartsWith(string key)
{
Context.Cache.InvalidateKeysByTag(key);
Remove(key);
}
public T Get<T>(string key) where T : class
{
var result = Context.Cache.GetObject<T>(key);
return result;
}
public object Get(string key)
{
var result = Context.Cache.GetObject<object>(key);
return result;
}
public void Remove(string key)
{
Context.Cache.Remove(key);
}
public bool Contains(string key)
{
var pattern = "*" + key + "*";
var contains = false;
var keys = Context.Cache.GetKeysByPattern(pattern).ToArray();
if (keys.Length > 0)
{
contains = true;
}
return contains;
}
public void Add(string key, object o, DateTimeOffset expiration, string dependsOnKey = null)
{
var exp = expiration - DateTime.Now;
if (dependsOnKey == null)
{
dependsOnKey = key;
}
else
{
dependsOnKey = APPICATION_KEY + dependsOnKey;
}
Context.Cache.SetObject(key, o, new string[] { dependsOnKey }, exp);
}
public IEnumerable<string> AllKeys { get; private set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment