Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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