在很多项目中, 需要用到缓存,借鉴网上前辈们的一些经验,自己再进行总结简化了一些, 做出如下的缓存操作,其中包含内存缓存(IMemoryCache) 和 Redis 缓存;

一.前提内容, 导入两个包:  Microsoft.Extensions.Caching.Memory   和 Microsoft.Extensions.Caching.Redis ,并在使用的类中using 一下它们.  我这里是用2.1.0版本的; 

二. 创建 ICacheService 公共接口 ,我这里写的比较简单, 如若业务需要可自行增加 异步和批量的接口方法.

 1 /// <summary>
 2     /// 缓存接口
 3     /// 分别内存缓存和Redis缓存(2.1.0版本)
 4     /// </summary>
 5     public interface ICacheService
 6     { 
 7         /// <summary>
 8         ///  新增
 9         /// </summary>
10         /// <param name="key"></param>
11         /// <param name="value"></param>
12         /// <param name="ExpirtionTime"></param>
13         /// <returns></returns>
14         bool Add(string key, object value, int ExpirtionTime = 20);
15 
16 
17         /// <summary>
18         /// 获取
19         /// </summary>
20         /// <param name="key"></param>
21         /// <returns></returns>
22         string GetValue(string key);
23         /// <summary>
24         /// 验证缓存项是否存在
25         /// </summary>
26         /// <param name="key">缓存Key</param>
27         /// <returns></returns>
28         bool Exists(string key);
29 
30         /// <summary>
31         /// 移除
32         /// </summary>
33         /// <param name="key"></param>
34         /// <returns></returns>
35         bool Remove(string key);
36     }

三. 再分别创建 MemoryCacheService 和RedisCacheService  类, 并继承 ICacheService 接口.

a.  MemoryCacheService  类  , 记得using 一下 Microsoft.Extensions.Caching.Memory

 /// <summary>
    /// 缓存接口实现
    /// </summary>
    public class MemoryCacheService : ICacheService
    {
        protected IMemoryCache _cache;

        public MemoryCacheService(IMemoryCache cache)
        {
            _cache = cache;
        }
         
        public bool Add(string key, object value, int ExpirtionTime = 20)
        {
            if (!string.IsNullOrEmpty(key))
            {
                _cache.Set(key, value , DateTimeOffset.Now.AddMinutes(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 string GetValue(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }
            if (Exists(key))
            {
                return _cache.Get(key).ToString();
            }
            return null;
        }
         
        public bool Exists(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return false;
            }

            object cache;
            return _cache.TryGetValue(key, out cache);
        }
         
    }
View Code

相关文章: