Created
May 31, 2015 23:15
-
-
Save gbellmann/750a3b0850c6f715d3a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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