据说是最全的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     /// <summary>
 12     /// auth @ zrf  2020-07-23
 13     /// </summary>
 14     public class SystemCacheHelper
 15     {
 16         private static IMemoryCache msCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
 17         private static readonly object obj = new object();
 18         //static SystemCacheHelper()
 19         //{
 20         //    msCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
 21         //}
 22         public static IMemoryCache CreateInstans()
 23         {
 24             if (msCache == null)
 25             {
 26                 lock (obj)
 27                 {
 28                     if (msCache == null)
 29                     {
 30                         msCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
 31                     }
 32                 }
 33             }
 34             return msCache;
 35         }
 36 
 37         /// <summary>
 38         /// 滑动过期/绝对过期
 39         /// </summary>
 40         /// <typeparam name="T"></typeparam>
 41         /// <param name="key"></param>
 42         /// <param name="model"></param>
 43         /// <param name="hd_ab">默认true :绝对过期,否则滑动过期</param>
 44         /// <param name="Minutes"></param>
 45         public static void SetCache<T>(string key, T model, bool hd_ab = true, int minutes = 3)
 46         {
 47             using (ICacheEntry entry = CreateInstans().CreateEntry(key))
 48             {
 49                 entry.Value = model;
 50                 if (hd_ab)
 51                 {
 52                     entry.AbsoluteExpiration = DateTime.Now.AddMinutes(minutes);
 53                 }
 54                 else
 55                 {
 56                     entry.SlidingExpiration = TimeSpan.FromMinutes(minutes);
 57                 }
 58             }
 59         }
 60 
 61         /// <summary>
 62         /// 文件依赖过期
 63         /// </summary>
 64         /// <typeparam name="T"></typeparam>
 65         /// <param name="key"></param>
 66         /// <param name="model"></param>
 67         public static void SetCacheByFile<T>(string key, T model)
 68         {
 69             using (ICacheEntry entry = CreateInstans().CreateEntry(key))
 70             {
 71                 entry.Value = model;
 72                 string filepath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cachefile.txt");
 73                 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filepath);
 74                 entry.AddExpirationToken(new Microsoft.Extensions.FileProviders.Physical.PollingFileChangeToken(fileInfo));
 75             }
 76         }
 77 
 78         /// <summary>
 79         /// 滑动过期
 80         /// </summary>
 81         /// <typeparam name="T"></typeparam>
 82         /// <param name="key"></param>
 83         /// <param name="model"></param>
 84         /// <param name="Minutes"></param>
 85         public static void SetCacheSliding<T>(string key, T model, int minutes = 3)
 86         {
 87             using (ICacheEntry entry = CreateInstans().CreateEntry(key))
 88             {
 89                 entry.Value = model;
 90                 entry.SlidingExpiration = TimeSpan.FromMinutes(minutes);
 91             }
 92         }
 93 
 94         /// <summary>
 95         /// 绝对过期
 96         /// </summary>
 97         /// <typeparam name="T"></typeparam>
 98         /// <param name="key"></param>
 99         /// <param name="model"></param>
100         /// <param name="Minutes"></param>
101         public static void SetCacheAbsolute<T>(string key, T model, int Minutes = 3)
102         {
103             using (ICacheEntry entry = CreateInstans().CreateEntry(key))
104             {
105                 entry.Value = model;
106                 entry.AbsoluteExpiration = DateTime.Now.AddMinutes(Minutes);
107             }
108         }
109         public static T GetByCache<T>(string key)
110         {
111             if (CreateInstans().TryGetValue(key, out T model))
112             {
113                 return model;
114             }
115             return default;
116         }
117     }
118 }
View Code

 6:进一步使用到自定义的配置文件中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ZRFCoreTestMongoDB.Commoms
{
    using ZRFCoreTestMongoDB.Model;
    using Microsoft.Extensions.Configuration;
    public class AppJsonHelper
    {
        public static JwtConfigModel InitJsonModel()
        {
            string key = "key_myjsonfilekey";
            JwtConfigModel cachemodel = SystemCacheHelper.GetByCache<JwtConfigModel>(key);
            if (cachemodel == null)
            {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                var broot = builder.AddJsonFile("./configs/zrfjwt.json").Build();
                cachemodel = broot.GetSection("jwtconfig").Get<JwtConfigModel>();
                SystemCacheHelper.SetCacheByFile<JwtConfigModel>(key, cachemodel);
            }
            return cachemodel;
        }
    }
}
View Code

猜你喜欢

转载自www.cnblogs.com/Fengge518/p/13366351.html