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 /// /// Retrive Cache Item by key /// /// /// /// public T GetCache(string key) where T : class { #region Stack Exchange Redis Cache T obj = null; try { obj = cacheClient.Get(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 /// /// Store Cache Item using Key & Object /// /// /// /// public void AddCache(string key, T t) { #region Stack Exchange Redis Cache cacheClient.Add(CacheKey(key), t, TimeSpan.FromMinutes(CacheExpireAt())); #endregion } /// /// Store Cache Item using Key & Object /// /// /// /// key will expire after the seconds /// public void AddCache(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 /// /// Remove All Cache Item /// public void RemoveCache() { #region User Exclude Keys List excludeCacheList = new List { 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); } /// /// Remove Cache Item By Key /// /// public void RemoveCacheByKey(string cacheKey) { cacheClient.Remove(CacheKey(cacheKey)); } /// /// Remove Cache Item By Key /// /// public void RemoveCacheByKeyStart(string cacheKey) { var keyList = cacheClient.SearchKeys(CacheKey(cacheKey) + "*"); cacheClient.RemoveAll(keyList); } #endregion #region Common /// /// Cache Key Construction /// /// /// private string CacheKey(string key) { return CacheHelper.CacheKey(key); } /// /// Reading cache expiration time from configuration /// /// public int CacheExpireAt() { return CacheHelper.CacheExpirationTime; } #endregion } }