个人测试环境为: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. PGSQL数据库里物化视图【materialized view】

    1.普通视图 数据库中的视图(view)是从一张或多张数据库表查询导出的虚拟表,反映基础表中数据的变化,且本身不存储数据. 2.物化视图[materialized view]     2.1.概念:  ...

  2. Python输出格式化

    参考链接:https://m.jb51.net/article/33631.htm 要求:以固定长度在中间输出某字符串,剩余部分用其他符号补齐.如:"Hello World"  - ...

  3. Cypress 高级用法系列 一

    1. Multiple Assertions cy .get('[data-cy=task]') .then( item => { expect(item[0]).to.contain.text ...

  4. 构建前端第9篇之(上)---Vue组件引入,使用

    张艳涛写于2020-1-25日 一.想写下vue引入组件和插件的理解 今天是星期一,周末也看俩两天,在这个几天了,比较迷,主要是从开始学习import指令开始的,import 是es6的语法, imp ...

  5. 基于ifix组态软件研究控制按钮权限

    背景: 在前阵子做基于ifix生成电力监控平台时,遇到业主提出的一个需求.关于如何在控制弹窗中,点击相应的合分闸按钮时,优先弹出登录界面,当输入相应的有权限用户名和密码后,才能操作这一要求.后实现如下 ...

  6. list实现从大到小排序

    public static void main(String[] args) { List<Integer> list=new ArrayList<Integer>(); // ...

  7. Winform中生成自动控件

    场景: 前几天项目需要模拟数据,但是实际设备还没有接上,就自己用Winform搭建了一个数据模拟器,生成数据给平台.这里又一个需求,就是从数据库中找出设备,然后自动生成控件,勾选就表示开启该设备,能上 ...

  8. Samba 远程命令执行漏洞(CVE-2017-7494)

    该漏洞影响Samba 3.5.0之后的所有版本,在4.6.4/4.5.10/4.4.14修复了这个漏洞 use exploit/linux/samba/is_known_pipename set rh ...

  9. SpringBoot数据访问之Druid数据源的使用

    数据访问之Druid数据源的使用 说明:该数据源Druid,使用自定义方式实现,后面文章使用start启动器实现,学习思路为主. 为什么要使用数据源: ​ 数据源是提高数据库连接性能的常规手段,数据源 ...

  10. 你的ES数据备份了吗?

    前言: 无论使用哪种存储软件,定期的备份数据都是重中之重,在使用ElasticSearch的时候,随着数据日益积累,存放es数据的磁盘空间也捉襟见肘, 此时对于业务功能使用不到的索引数据,又不能直接删 ...