asp.NetCore3.1系统自带Imemcache缓存-滑动/绝对/文件依赖的缓存使用测试
阅读原文时间:2023年07月12日阅读:1

个人测试环境为:Asp.net coe 3.1 WebApi

1:封装自定义的cacheHelper帮助类,部分代码

1 public static void SetCacheByFile(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 }

2:在startUp类中 注册方法:

services.AddMemoryCache();//注册使用缓存

3:测试代码

[HttpGet, Route("DocacheByFIle")]
public ApiResult DoSystemFileCacheTest()
{
ApiResult result = new ApiResult();
try
{
string time = SystemCacheHelper.GetByCache("Filecache");
if (string.IsNullOrEmpty(time))
{
var gettime = "你好峰哥,我是文件依赖的缓存" + DateTime.Now.ToString();
SystemCacheHelper.SetCacheByFile("Filecache", gettime);
time = gettime;
}
result.data = time;
result.code = statuCode.success;
result.message = "获取cache数据成功!";
}
catch (Exception ex)
{
result.message = "发生异常:" + ex.Message;
}
return result;
}

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 ///

12 /// auth @ zrf 2020-07-23 13 ///
14 public class SystemCacheHelper
15 {
16 private static IMemoryCache msCache = null;// 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 /// 38 /// 滑动过期/绝对过期 39 ///
40 ///
41 ///
42 ///
43 /// 默认true :绝对过期,否则滑动过期
44 ///
45 public static void SetCache(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 /// 62 /// 文件依赖过期 63 ///
64 ///
65 ///
66 ///
67 public static void SetCacheByFile(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 /// 79 /// 滑动过期 80 ///
81 ///
82 ///
83 ///
84 ///
85 public static void SetCacheSliding(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 /// 95 /// 绝对过期 96 ///
97 ///
98 ///
99 ///
100 ///
101 public static void SetCacheAbsolute(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(string key)
110 {
111 if (CreateInstans().TryGetValue(key, out T model))
112 {
113 return model;
114 }
115 return default;
116 }
117 }
118 }

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(key);
if (cachemodel == null)
{
ConfigurationBuilder builder = new ConfigurationBuilder();
var broot = builder.AddJsonFile("./configs/zrfjwt.json").Build();
cachemodel = broot.GetSection("jwtconfig").Get();
SystemCacheHelper.SetCacheByFile(key, cachemodel);
}
return cachemodel;
}
}
}

7:模型

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

namespace ZRFCoreTestMongoDB.Model
{
public class JwtConfigModel
{
public string TockenSecrete { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
}
}

8:测试完整代码:

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Threading.Tasks;
5
6 namespace ZRFCoreTestMongoDB.Controllers
7 {
8 using Microsoft.AspNetCore.Authorization;
9 using Microsoft.AspNetCore.Mvc.Filters;
10 using Microsoft.AspNetCore.Mvc;
11 using ZRFCoreTestMongoDB.Model;
12 using ZRFCoreTestMongoDB.Commoms;
13 [ApiController]
14 [Route("api/[Controller]")]
15 public class MyJwtTestController : ControllerBase
16 {
17 private readonly JwtConfigModel _jsonmodel;
18 public MyJwtTestController()
19 {
20 _jsonmodel = AppJsonHelper.InitJsonModel();
21 }
22 [HttpGet, Route("jsonmodel")]
23 public ApiResult DoMyselfJsonTest()
24 {
25 ApiResult result = new ApiResult();
26 try
27 {
28 result.data = _jsonmodel;
29 result.code = statuCode.success;
30 result.message = "获取数据成功!";
31 }
32 catch (Exception ex)
33 {
34 result.message = "发生异常:" + ex.Message;
35 }
36 return result;
37 }
38 [HttpGet, Route("testcache")]
39 public ApiResult DoSystemCacheTest()
40 {
41 ApiResult result = new ApiResult();
42 try
43 {
44 string time = SystemCacheHelper.GetByCache("nowtime");
45 if (string.IsNullOrEmpty(time))
46 {
47 var gettime = "为:" + DateTime.Now.ToString();
48 SystemCacheHelper.SetCache("nowtime", gettime, minutes: 1);
49 time = gettime;
50 }
51 result.data = time;
52 result.code = statuCode.success;
53 result.message = "获取cache数据成功!";
54 }
55 catch (Exception ex)
56 {
57 result.message = "发生异常:" + ex.Message;
58 }
59 return result;
60 }
61 [HttpGet, Route("DocacheByFIle")]
62 public ApiResult DoSystemFileCacheTest()
63 {
64 ApiResult result = new ApiResult();
65 try
66 {
67 string time = SystemCacheHelper.GetByCache("Filecache");
68 if (string.IsNullOrEmpty(time))
69 {
70 var gettime = "你好峰哥,我是文件依赖的缓存" + DateTime.Now.ToString();
71 SystemCacheHelper.SetCacheByFile("Filecache", gettime);
72 time = gettime;
73 }
74 result.data = time;
75 result.code = statuCode.success;
76 result.message = "获取cache数据成功!";
77 }
78 catch (Exception ex)
79 {
80 result.message = "发生异常:" + ex.Message;
81 }
82 return result;
83 }
84 }
85 }

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 ZRFCoreTestMongoDB.Model;
9 using Microsoft.Extensions.Configuration;
10 public class AppJsonHelper
11 {
12 public static JwtConfigModel InitJsonModel()
13 {
14 string key = "key_myjsonfilekey";
15 JwtConfigModel cachemodel = SystemCacheHelper.GetByCache(key);
16 if (cachemodel == null)
17 {
18 ConfigurationBuilder builder = new ConfigurationBuilder();
19 var broot = builder.AddJsonFile("./configs/zrfjwt.json").Build();
20 cachemodel = broot.GetSection("jwtconfig").Get();
21 SystemCacheHelper.SetCacheByFile(key, cachemodel);
22 }
23 return cachemodel;
24 }
25 }
26 }