Skip to content

Instantly share code, notes, and snippets.

@nowsathns
Last active September 29, 2019 10:27
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 nowsathns/99e11ccde73bc3157b6657f20db1bce8 to your computer and use it in GitHub Desktop.
Save nowsathns/99e11ccde73bc3157b6657f20db1bce8 to your computer and use it in GitHub Desktop.
Redis Cache Manager Class
using Autofac;
using Hangfire;
using StackExchange.Redis;
using StackExchange.Redis.Extensions.Core;
using StackExchange.Redis.Extensions.MsgPack;
using System;
using System.Configuration;
using System.Runtime.Caching;
namespace TestApp02.Utility
{
public static class CacheRegistration
{
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => { return GetConnectionMultiplexer(cacheConfig.Redis.HostName); }, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
public static ConnectionMultiplexer Connection { get { return lazyConnection.Value; } }
public static void AutofacInitialize(ContainerBuilder builder)
{
CacheHelper.CacheExpirationTime = 180;
builder.Register(c => new MsgPackObjectSerializer()).As<ISerializer>().InstancePerRequest();
builder.Register(c => new StackExchangeRedisCacheClient(Connection, c.Resolve<ISerializer>(), cacheConfig.Redis.Database)).As<ICacheClient>().InstancePerRequest();
builder.RegisterType<RedisCacheManager>().As<ICacheManager>().InstancePerRequest();
}
public static ConnectionMultiplexer GetConnectionMultiplexer(string hosts)
{
ConfigurationOptions options = new ConfigurationOptions();
try
{
options.Ssl = (cacheConfig.Redis.Ssl == 1);
options.SyncTimeout = cacheConfig.Redis.syncTimeout;
options.AbortOnConnectFail = false;
options.ConnectRetry = 5;
options.DefaultDatabase = cacheConfig.Redis.Database;
if (!string.IsNullOrEmpty(cacheConfig.Redis.Password))
{ options.Password = cacheConfig.Redis.Password; }
//options.ReconnectRetryPolicy = new LinearRetry(5000);
foreach (var item in hosts.Split(','))
{
if (string.IsNullOrEmpty(item)) { continue; }
options.EndPoints.Add(item, cacheConfig.Redis.Port);
}
return ConnectionMultiplexer.Connect(options);
}
finally
{
options = null;
}
}
}
}
using Newtonsoft.Json;
using StackExchange.Redis;
using StackExchange.Redis.Extensions.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestApp02.Utility.Cache
{
public class RedisCacheManager : ICacheManager
{
#region Constructor
private readonly ICacheClient cacheClient;
public RedisCacheManager(ICacheClient _cacheClient)
{
cacheClient = _cacheClient;
}
#endregion
#region Retrive Cache Item
/// <summary>
/// Retrive Cache Item by key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T GetCache<T>(string key) where T : class
{
#region Stack Exchange Redis Cache
T obj = null;
try
{
obj = cacheClient.Get<T>(CacheKey(key), StackExchange.Redis.CommandFlags.PreferSlave);
return obj;
}
catch (Exception)
{
// this.loggerService.Error(e);
return null;
}
finally
{
obj = null;
}
#endregion
}
#endregion
#region Store Cache Item
/// <summary>
/// Store Cache Item using Key & Object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="t"></param>
public void AddCache<T>(string key, T t)
{
#region Stack Exchange Redis Cache
cacheClient.Add(CacheKey(key), t, TimeSpan.FromMinutes(CacheExpireAt()));
#endregion
}
/// <summary>
/// Store Cache Item using Key & Object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="seconds">key will expire after the seconds</param>
/// <param name="t"></param>
public void AddCache<T>(string key, int seconds, T t)
{
#region Stack Exchange Redis Cache
cacheClient.Add(CacheKey(key), t, TimeSpan.FromSeconds(seconds));
//cacheClient.Database.KeyTimeToLive(key, StackExchange.Redis.CommandFlags.None);
#endregion
}
#endregion
#region Remove Cache Item
/// <summary>
/// Remove All Cache Item
/// </summary>
public void RemoveCache()
{
#region User Exclude Keys
List<string> excludeCacheList = new List<string> { CacheKey(CacheHelper.CacheGroupKeys.UserSessions.ToString()) };
#endregion
var keyList = cacheClient.SearchKeys(CacheHelper.CacheApplicationCode + "*");
var cacheKeyList = keyList.Where(exp => !excludeCacheList.Any(key => exp.Contains(key)));
cacheClient.RemoveAll(cacheKeyList);
}
/// <summary>
/// Remove Cache Item By Key
/// </summary>
/// <param name="cacheKey"></param>
public void RemoveCacheByKey(string cacheKey)
{
cacheClient.Remove(CacheKey(cacheKey));
}
/// <summary>
/// Remove Cache Item By Key
/// </summary>
/// <param name="cacheKey"></param>
public void RemoveCacheByKeyStart(string cacheKey)
{
var keyList = cacheClient.SearchKeys(CacheKey(cacheKey) + "*");
cacheClient.RemoveAll(keyList);
}
#endregion
#region Common
/// <summary>
/// Cache Key Construction
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private string CacheKey(string key)
{
return CacheHelper.CacheKey(key);
}
/// <summary>
/// Reading cache expiration time from configuration
/// </summary>
/// <returns></returns>
public int CacheExpireAt()
{
return CacheHelper.CacheExpirationTime;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment