Skip to content

Instantly share code, notes, and snippets.

@pradeepn
Created February 20, 2021 13:22
Show Gist options
  • Save pradeepn/95ae0a8b2fe44af90417828705e95aae to your computer and use it in GitHub Desktop.
Save pradeepn/95ae0a8b2fe44af90417828705e95aae to your computer and use it in GitHub Desktop.
Redis Store Implementation
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DistributedCaching.Core
{
public static class RedisStore
{
private static Lazy<ConnectionMultiplexer> _redisConnection;
private static string _host;
private static string _port;
static RedisStore()
{
_host = ConfigurationManager.AppSettings["Redis:Host"].ToString();
_port = ConfigurationManager.AppSettings["Redis:Port"].ToString();
RedisStore._redisConnection = new Lazy<ConnectionMultiplexer>(() =>
{
return ConnectionMultiplexer.Connect(_host);
});
}
public static ConnectionMultiplexer Connection
{
get
{
return _redisConnection.Value;
}
}
public static IDatabase Cache
{
get
{
return Connection.GetDatabase();
}
}
public static IServer Server
{
get
{
return Connection.GetServer($"{_host}:{_port}");
}
}
}
public static class SerializeUtils
{
#region JSON
public static string Serialize<T>(this T obj)
{
return JsonConvert.SerializeObject(obj);
}
public static T Deserialize<T>(this string str)
{
return JsonConvert.DeserializeObject<T>(str);
}
#endregion
#region Redis
//Serialize in Redis format:
public static HashEntry[] ToHashEntries(this object obj)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
return properties.Where(x => x.GetValue(obj) != null).Select(property => new HashEntry(property.Name, property.GetValue(obj).ToString())).ToArray();
}
//Deserialize from Redis format
public static T ConvertFromRedis<T>(this HashEntry[] hashEntries)
{
PropertyInfo[] properties = typeof(T).GetProperties();
var obj = Activator.CreateInstance(typeof(T));
foreach (var property in properties)
{
HashEntry entry = hashEntries.FirstOrDefault(g => g.Name.ToString().Equals(property.Name));
if (entry.Equals(new HashEntry())) continue;
property.SetValue(obj, Convert.ChangeType(entry.Value.ToString(), property.PropertyType));
}
return (T)obj;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment