Skip to content

Instantly share code, notes, and snippets.

@gbellmann
Created May 31, 2015 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbellmann/750a3b0850c6f715d3a7 to your computer and use it in GitHub Desktop.
Save gbellmann/750a3b0850c6f715d3a7 to your computer and use it in GitHub Desktop.
using System;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace RedisCache
{
public static class CacheExtensions
{
public static T Get<T>(this IDatabase cache, string key)
{
return Deserialize<T>(cache.StringGet(string.Format("{0}-{1}", typeof(T).Name, key)));
}
public static object Get(this IDatabase cache, string key)
{
return Deserialize<object>(cache.StringGet(key));
}
public static void Set(this IDatabase cache, string key, object value)
{
cache.StringSet(key, Serialize(value));
}
public static void Set(this IDatabase cache, string key, object value, TimeSpan expiration)
{
cache.StringSet(key, Serialize(value), expiration);
}
public static void Set<T>(this IDatabase cache, string key, T value)
{
cache.StringSet(string.Format("{0}-{1}", typeof(T).Name, key), Serialize(value));
}
public static void Set<T>(this IDatabase cache, string key, T value, TimeSpan expiration)
{
cache.StringSet(string.Format("{0}-{1}", typeof(T).Name, key), Serialize(value), expiration);
}
static string Serialize<T>(T o)
{
if (o == null)
{
return null;
}
return JsonConvert.SerializeObject(o);
}
static T Deserialize<T>(string objectString)
{
if (string.IsNullOrWhiteSpace(objectString))
{
return default(T);
}
return JsonConvert.DeserializeObject<T>(objectString);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment