Net core 關於緩存的實現


在很多項目中, 需要用到緩存,借鑒網上前輩們的一些經驗,自己再進行總結簡化了一些, 做出如下的緩存操作,其中包含內存緩存(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

b. RedisCacheService 類  , 記得using 一下 Microsoft.Extensions.Caching.Redis

public  class RedisCacheService:ICacheService
    {
        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.AddMinutes(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;
        }
        
    }
View Code

四.  在 Startup.cs  文件中注入 Redis 和Memory.  這里啰嗦多幾句, 因為同一個接口注入了多個實現,  那到調用的時候, 容器是怎么知道調用哪個類呢?   我這里是參考了  

ASP.NET Core默認注入方式下如何注入多個實現(多種方式)  ,  

            services.AddTransient<MemoryCacheService>(); //內存緩存認證注入 
            //注入Redis
            services.AddSingleton(new RedisCacheService(new RedisCacheOptions()
            {
                InstanceName = Configuration.GetSection("Redis:InstanceName").Value,
                Configuration= Configuration.GetSection("Redis:Connection").Value
            }));

並在appsettings.json配置redis , 

 "Redis": {
    "Connection": "127.0.0.1:6379",
    "InstanceName": "Redis:"
  }

服務調用我使用了IServiceProvider  .

調用如下: 

 

 五.總結   

總算是寫了一篇讓自己看得懂一些的文章了.   行吧...算是一個小進步吧!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM