个人测试环境为: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 }

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;
}

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

 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;
}
}
}

 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<string>("nowtime");
45 if (string.IsNullOrEmpty(time))
46 {
47 var gettime = "为:" + DateTime.Now.ToString();
48 SystemCacheHelper.SetCache<string>("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<string>("Filecache");
68 if (string.IsNullOrEmpty(time))
69 {
70 var gettime = "你好峰哥,我是文件依赖的缓存" + DateTime.Now.ToString();
71 SystemCacheHelper.SetCacheByFile<string>("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<JwtConfigModel>(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<JwtConfigModel>();
21 SystemCacheHelper.SetCacheByFile<JwtConfigModel>(key, cachemodel);
22 }
23 return cachemodel;
24 }
25 }
26 }

asp.NetCore3.1系统自带Imemcache缓存-滑动/绝对/文件依赖的缓存使用测试的更多相关文章

  1. 系统自带的NSJSONSerialization解析json文件

    #import "ViewController.h" #import "Student.h" #import "GDataXMLNode.h" ...

  2. (转)Android调用系统自带的文件管理器进行文件选择并获得路径

    Android区别于iOS的沙盒模式,可以通过文件浏览器浏览本地的存储器.Android API也提供了相应的接口. 基本思路,先通过Android API调用系统自带的文件浏览器选取文件获得URI, ...

  3. Android调用系统自带的文件管理器进行文件选择并读取

    先调用: intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); //设置类型,我这里是任意类 ...

  4. Android调用系统自带的文件管理器进行文件选择

    http://blog.csdn.net/zqchn/article/details/8770913的补充 FileUtils文件 public class FileUtils {     publi ...

  5. iOS开发——运行时OC篇&使用运行时获取系统的属性:使用自己的手势修改系统自带的手势

    使用运行时获取系统的属性:使用自己的手势修改系统自带的手势 有的时候我需要实现一个功能,但是没有想到很好的方法或者想到了方法只是那个方法实现起来太麻烦,一或者确实为了装逼,我们就会想到iOS开发中最牛 ...

  6. django之缓存的用法, 文件形式与 redis的基本使用

    django的缓存的用法讲解 1. django缓存: 缓存的机制出现主要是缓解了数据库的压力而存在的 2. 动态网站中,用户的请求都会去数据库中进行相应的操作,缓存的出现是提高了网站的并发量 3. ...

  7. 最近开始研究php的缓存技术,来个系统自带的OPcache

    最近开始研究php的缓存技术,来个系统自带的OPcache php5.5以上版本  系统自带 PHP5.2-5.4 可通过扩展来安装 OPcache是 zend出品  比apc的优势在于  长期更新 ...

  8. Asp.Net framework 类库 自带的缓存 HttpRuntime.Cache HttpContext.Cache

    两个Cache 在.NET运用中经常用到缓存(Cache)对象.有HttpContext.Current.Cache以及HttpRuntime.Cache,HttpRuntime.Cache是应用程序 ...

  9. ASP.NET MVC 系统过滤器、自定义过滤器

    一.系统过滤器使用说明 1.OutputCache过滤器 OutputCache过滤器用于缓存你查询结果,这样可以提高用户体验,也可以减少查询次数.它有以下属性: Duration:缓存的时间,以秒为 ...

随机推荐

  1. Linux服务系统申请SSL证书方法

    inux主要面向专业性较强的技术人员,如果是WEB站点通常采取PHP语言为主选,可选的服务器环境中有Apache.Nginx.Tomcat这几类为主的框架环境,有的图方便会用一些可视化一键式的控制面板 ...

  2. router-link与router-view的对应关系和映射特点

    router-link对应的router-view规律为: 1.根据to的值而定,值为一层(如 /child)则对应app.vue中的router-view: 值为两层,如 /second/child ...

  3. [考试总结]noip模拟23

    因为考试过多,所以学校的博客就暂时咕掉了,放到家里来写 不过话说,vscode的markdown编辑器还是真的很好用 先把 \(noip\) 模拟 \(23\) 的总结写了吧.. 俗话说:" ...

  4. Vue项目发布的问题--http://localhost:8088/static/fonts/fontawesome-webfont.af7ae50.woff2

    问题:ngnix将8080转成80对外访问,找不对woff2等文件 一\ 搭建环境 ngnix-->conf中 server { listen 80; server_name 10.9.240. ...

  5. videojs文档翻译-EventTarget

    EventTarget new EventTarget()   EventTarget是一个可以与DOM EventTarget具有相同API的类. 它增加了包含冗长功能的缩写功能. 例如:on函数是 ...

  6. php-socket通信演示

    client: error_reporting(E_ALL); set_time_limit(0); echo "<h2>TCP/IP Connection</h2> ...

  7. 题解 P6688 可重集

    己所欲者,杀而夺之,亦同天赐 解题思路 一定不要用自动溢出的 Hash!!!!!!! 我真的是调吐了... 思路非常简单明了 : 需要我们创新一下 Hash. 首先我们的 Hash 要满足无序性.. ...

  8. jmeter永久调为中文

    将jmeter调为中文有两种方法,一是在软件设置中切换,二是修改配置文件. 第一种方式是临时的,下次重新打开会变回为英文 第二种方式是永久的,每次打开都会显示自己配置好的语言 第一种方式: 第二种方式 ...

  9. 代码部署:使用 nginx 代理到云服务器 ( windows 系统)

    在部署之前我们首先要了解什么是nginx,它又可以做什么 Nginx 是高性能的 HTTP 和反向代理的web服务器,处理高并发能力是十分强大的,能经受高负 载的考验,有报告表明能支持高达 50,00 ...

  10. PaddlePaddle之猫狗大战(本地数据集)

    新手入门PaddlePaddle的一个简单Demo--猫狗大战 主要目的在于整体了解PP用卷积做图像分类的流程,以及最最重要的掌握自定义数据集的读取方式 猫狗数据集是从网络上下载到工作目录的. 本项目 ...