cache缓存帮助类
缓存帮助类:
public class CacheHelper { //ConcurrentDictionary<object, CacheEntry> _entries //public static MemoryCache //缓存容器 private static ConcurrentDictionary<string, object> CacheDictionary = new ConcurrentDictionary<string, object>(); /// <summary> /// 添加缓存 /// </summary> public static bool Add(string key, object value) { //CacheDictionary.Add(key, value); return CacheDictionary.TryAdd(key, value); } /// <summary> /// 获取缓存 /// </summary> public static T Get<T>(string key) { return (T)CacheDictionary[key]; } /// <summary> /// 缓存获取方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">缓存字典容器对应key</param> /// <param name="func">委托方法 传入操作对象</param> /// <returns></returns> public static T GetCache<T>(string key, Func<T> func) { T t = default(T); if (CacheHelper.Exsits(key)) { //缓存存在,直接获取原数据 t = CacheHelper.Get<T>(key); } else { //缓存不存在,去生成缓存,并加入容器 t = func.Invoke(); CacheHelper.Add(key, t); } return t; } /// <summary> /// 判断缓存是否存在 /// </summary> /// <param name="key"></param> /// <returns></returns> public static bool Exsits(string key) { return CacheDictionary.ContainsKey(key); } /// <summary> /// 移除 /// </summary> /// <param name="key"></param> public static void Remove(string key) { if (CacheDictionary.ContainsKey(key)) { CacheDictionary.TryRemove(key,out _); } } }
接口类:
/// <summary> /// 缓存接口(分别内存缓存和Redis缓存) /// </summary> public interface ICacheService { /// <summary> /// 新增 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">缓存Value</param> /// <param name="ExpirtionTime">过期时间</param> /// <returns></returns> bool Add(string key, object value, int ExpirtionTime = 20); /// <summary> /// 设置缓存,并指定绝对超时时间 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteTimeoutSeconds">绝对超时时间</param> void SetValue<T>(string key, T value, int absoluteTimeoutSeconds); /// <summary> /// 设置缓存,并设定超时时间,不访问(滑动)超时时间 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteTimeoutSeconds">绝对超时时间</param> /// <param name="slidingExpirationSeconds">不访问超时时间(在这个指定的时段内没有使用则过期,否则顺延)</param> void SetValue<T>(string key, T value, int absoluteTimeoutSeconds, int slidingExpirationSeconds); /// <summary> /// 移除 /// </summary> /// <param name="key">缓存Key</param> /// <returns></returns> bool Remove(string key); /// <summary> /// 获取 /// </summary> /// <param name="key"></param> /// <returns></returns> string GetValue(string key); /// <summary> /// 验证缓存项是否存在 /// </summary> /// <param name="key">缓存Key</param> /// <returns></returns> bool Exists(string key); }
缓存接口实现:
/// <summary> /// 缓存接口实现 /// </summary> public class MemoryCacheService : ICacheService { //services.AddMemoryCache(options => { // // 缓存最大为100份 // //##注意netcore中的缓存是没有单位的,缓存项和缓存的相对关系 // options.SizeLimit = 2; // //缓存满了时候压缩20%的优先级较低的数据 // options.CompactionPercentage = 0.2; // //两秒钟查找一次过期项 // options.ExpirationScanFrequency = TimeSpan.FromSeconds(2); //}); protected IMemoryCache _cache; public MemoryCacheService(IMemoryCache cache) { _cache = cache; } public bool Add(string key, object value, int ExpirtionTime = 20) { if (!string.IsNullOrEmpty(key)) { //MemoryCacheEntryOptions cacheEntityOps = new MemoryCacheEntryOptions() //{ // //滑动过期时间 20秒没有访问则清除 // SlidingExpiration = TimeSpan.FromSeconds(ExpirtionTime), // //设置份数 // Size = 1, // //优先级 // Priority = CacheItemPriority.Low, // //AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(ExpirtionTime), //}; ////过期回掉 //cacheEntityOps.RegisterPostEvictionCallback((keyInfo, valueInfo, reason, state) => //{ // Console.WriteLine($"回调函数输出【键:{keyInfo},值:{valueInfo},被清除的原因:{reason}】"); //}); //_cache.Set(key, value, cacheEntityOps); _cache.Set(key, value, DateTimeOffset.Now.AddSeconds(ExpirtionTime)); } return true; } public bool Remove(string key) { if (string.IsNullOrEmpty(key)) { return false; } if (Exists(key)) { _cache.Remove(key); return true; } return false; } public bool Exists(string key) { if (string.IsNullOrEmpty(key)) { return false; } object cache; return _cache.TryGetValue(key, out cache); } public string GetValue(string key) { if (string.IsNullOrEmpty(key)) { return null; } if (Exists(key)) { return _cache.Get(key).ToString(); } return null; } public void SetValue<T>(string key, T value, int absoluteTimeoutSeconds) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } T t; if (_cache.TryGetValue<T>(key, out t)) { _cache.Remove(key); } _cache.Set<T>(key, value, DateTimeOffset.Now.AddSeconds(absoluteTimeoutSeconds)); } public void SetValue<T>(string key, T value, int absoluteTimeoutSeconds, int slidingExpirationSeconds) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } T t; if (_cache.TryGetValue<T>(key, out t)) { _cache.Remove(key); } _cache.Set(key, value, new MemoryCacheEntryOptions() { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(absoluteTimeoutSeconds), //绝对超时时间, SlidingExpiration = TimeSpan.FromSeconds(slidingExpirationSeconds), //不访问超时时间(在这个指定的时段内没有使用则过期,否则顺延) }); } }
Redis缓存Microsoft.Extensions.Caching.Redis
/// <summary> /// Redis缓存Microsoft.Extensions.Caching.Redis /// </summary> public class RedisCacheService : ICacheService { ////Microsoft.Extensions.Caching.Redis ////注入Redis //services.AddSingleton(new RedisCacheService(new RedisCacheOptions() //{ // InstanceName = Configuration.GetSection("Redis:InstanceName").Value, // Configuration = Configuration.GetSection("Redis:Connection").Value //})); //"Redis": { // "Connection": "127.0.0.1:6379", // "InstanceName": "Redis:" // } protected RedisCache _redisCache = null; public RedisCacheService(RedisCacheOptions options) { _redisCache = new RedisCache(options); } public bool Add(string key, object value, int ExpirtionTime = 20) { if (!string.IsNullOrEmpty(key)) { _redisCache.Set(key, Encoding.UTF8.GetBytes(value.ToString()), new DistributedCacheEntryOptions() { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(ExpirtionTime) }); } return true; } public bool Remove(string key) { if (string.IsNullOrEmpty(key)) { return false; } if (Exists(key)) { _redisCache.Remove(key); return true; } return false; } public string GetValue(string key) { if (string.IsNullOrEmpty(key)) { return null; } if (Exists(key)) { return _redisCache.GetString(key); } return null; } public bool Exists(string key) { if (string.IsNullOrEmpty(key)) { return false; } return !string.IsNullOrEmpty(_redisCache.GetString(key)) ? true : false; } public void SetValue<T>(string key, T value, int absoluteTimeoutSeconds) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (!string.IsNullOrEmpty(_redisCache.GetString(key))) { _redisCache.Remove(key); } _redisCache.Set(key, Encoding.UTF8.GetBytes(value.ToString()), new DistributedCacheEntryOptions() { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(absoluteTimeoutSeconds) }); } public void SetValue<T>(string key, T value, int absoluteTimeoutSeconds, int slidingExpirationSeconds) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (!string.IsNullOrEmpty(_redisCache.GetString(key))) { _redisCache.Remove(key); } _redisCache.Set(key, Encoding.UTF8.GetBytes(value.ToString()), new DistributedCacheEntryOptions() { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(absoluteTimeoutSeconds), //绝对超时时间, SlidingExpiration = TimeSpan.FromSeconds(slidingExpirationSeconds), //不访问超时时间(在这个指定的时段内没有使用则过期,否则顺延) }); } }