1. 程式人生 > 實用技巧 >最全的asp.NetCore3.1系統自帶快取Imemcache的滑動絕對檔案依賴的測試使用

最全的asp.NetCore3.1系統自帶快取Imemcache的滑動絕對檔案依賴的測試使用

個人測試環境為:Asp.net coe 3.1 WebApi

1:封裝自定義的cacheHelper幫助類,部分程式碼

 1   public static void SetCacheByFile<T>(string key, T model)
 2         {
 3             using (ICacheEntry entry = CreateInstans().CreateEntry(key))
 4             {
 5                 entry.Value = model;
 6                 string
filepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cachefile.txt"); 7 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filepath); 8 entry.AddExpirationToken(new Microsoft.Extensions.FileProviders.Physical.PollingFileChangeToken(fileInfo));
9 } 10 }
View Code

2:在startUp類中 註冊方法:

services.AddMemoryCache();//註冊使用快取

3:測試程式碼

 [HttpGet, Route("DocacheByFIle")]
        public ApiResult DoSystemFileCacheTest()
        {
            ApiResult result = new ApiResult();
            try
            {
                string time = SystemCacheHelper.GetByCache<string
>("Filecache"); if (string.IsNullOrEmpty(time)) { var gettime = "你好峰哥,我是檔案依賴的快取" + DateTime.Now.ToString(); SystemCacheHelper.SetCacheByFile<string>("Filecache", gettime); time = gettime; } result.data = time; result.code = statuCode.success; result.message = "獲取cache資料成功!"; } catch (Exception ex) { result.message = "發生異常:" + ex.Message; } return result; }
View Code

4:檔案依賴過期的測試效果截圖:

4.1:當檔案沒有被修改,多次重新整理請求,快取的資料沒有變化,到達了效果

4.2:當檔案內容有修改,重新請求介面發現快取的資料有變化,到達了預期的效果

5: 其他的測試也ok,這裡就不貼出來了,下面為全部的cacheHelper幫助類的程式碼:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Threading.Tasks;
  5 
  6 namespace ZRFCoreTestMongoDB.Commoms
  7 {
  8     using Microsoft.Extensions.Caching.Memory;
  9     using Microsoft.Extensions.Options;
 10     using ZRFCoreTestMongoDB.Model;
 11     public class SystemCacheHelper
 12     {
 13         private static IMemoryCache msCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
 14         private static readonly object obj = new object();
 15         //static SystemCacheHelper()
 16         //{
 17         //    msCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
 18         //}
 19         public static IMemoryCache CreateInstans()
 20         {
 21             if (msCache == null)
 22             {
 23                 lock (obj)
 24                 {
 25                     if (msCache == null)
 26                     {
 27                         msCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
 28                     }
 29                 }
 30             }
 31             return msCache;
 32         }
 33 
 34         /// <summary>
 35         /// 滑動過期/絕對過期
 36         /// </summary>
 37         /// <typeparam name="T"></typeparam>
 38         /// <param name="key"></param>
 39         /// <param name="model"></param>
 40         /// <param name="hd_ab">預設true :絕對過期,否則滑動過期</param>
 41         /// <param name="Minutes"></param>
 42         public static void SetCache<T>(string key, T model, bool hd_ab = true, int minutes = 3)
 43         {
 44             using (ICacheEntry entry = CreateInstans().CreateEntry(key))
 45             {
 46                 entry.Value = model;
 47                 if (hd_ab)
 48                 {
 49                     entry.AbsoluteExpiration = DateTime.Now.AddMinutes(minutes);
 50                 }
 51                 else
 52                 {
 53                     entry.SlidingExpiration = TimeSpan.FromMinutes(minutes);
 54                 }
 55             }
 56         }
 57 
 58         public static void SetCacheByFile<T>(string key, T model)
 59         {
 60             using (ICacheEntry entry = CreateInstans().CreateEntry(key))
 61             {
 62                 entry.Value = model;
 63                 string filepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cachefile.txt");
 64                 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filepath);
 65                 entry.AddExpirationToken(new Microsoft.Extensions.FileProviders.Physical.PollingFileChangeToken(fileInfo));
 66             }
 67         }
 68 
 69         /// <summary>
 70         /// 滑動過期
 71         /// </summary>
 72         /// <typeparam name="T"></typeparam>
 73         /// <param name="key"></param>
 74         /// <param name="model"></param>
 75         /// <param name="Minutes"></param>
 76         public static void SetCacheSliding<T>(string key, T model, int minutes = 3)
 77         {
 78             using (ICacheEntry entry = CreateInstans().CreateEntry(key))
 79             {
 80                 entry.Value = model;
 81                 entry.SlidingExpiration = TimeSpan.FromMinutes(minutes);
 82             }
 83         }
 84 
 85         /// <summary>
 86         /// 絕對過期
 87         /// </summary>
 88         /// <typeparam name="T"></typeparam>
 89         /// <param name="key"></param>
 90         /// <param name="model"></param>
 91         /// <param name="Minutes"></param>
 92         public static void SetCacheAbsolute<T>(string key, T model, int Minutes = 3)
 93         {
 94             using (ICacheEntry entry = CreateInstans().CreateEntry(key))
 95             {
 96                 entry.Value = model;
 97                 entry.AbsoluteExpiration = DateTime.Now.AddMinutes(Minutes);
 98             }
 99         }
100         public static T GetByCache<T>(string key)
101         {
102             if (CreateInstans().TryGetValue(key, out T model))
103             {
104                 return model;
105             }
106             return default;
107         }
108     }
109 }
View Code