Created
February 20, 2021 13:22
-
-
Save pradeepn/95ae0a8b2fe44af90417828705e95aae to your computer and use it in GitHub Desktop.
Redis Store Implementation
This file contains hidden or 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 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