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 }
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缓存-滑动/绝对/文件依赖的缓存使用测试的更多相关文章
- 系统自带的NSJSONSerialization解析json文件
#import "ViewController.h" #import "Student.h" #import "GDataXMLNode.h" ...
- (转)Android调用系统自带的文件管理器进行文件选择并获得路径
Android区别于iOS的沙盒模式,可以通过文件浏览器浏览本地的存储器.Android API也提供了相应的接口. 基本思路,先通过Android API调用系统自带的文件浏览器选取文件获得URI, ...
- Android调用系统自带的文件管理器进行文件选择并读取
先调用: intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); //设置类型,我这里是任意类 ...
- Android调用系统自带的文件管理器进行文件选择
http://blog.csdn.net/zqchn/article/details/8770913的补充 FileUtils文件 public class FileUtils { publi ...
- iOS开发——运行时OC篇&使用运行时获取系统的属性:使用自己的手势修改系统自带的手势
使用运行时获取系统的属性:使用自己的手势修改系统自带的手势 有的时候我需要实现一个功能,但是没有想到很好的方法或者想到了方法只是那个方法实现起来太麻烦,一或者确实为了装逼,我们就会想到iOS开发中最牛 ...
- django之缓存的用法, 文件形式与 redis的基本使用
django的缓存的用法讲解 1. django缓存: 缓存的机制出现主要是缓解了数据库的压力而存在的 2. 动态网站中,用户的请求都会去数据库中进行相应的操作,缓存的出现是提高了网站的并发量 3. ...
- 最近开始研究php的缓存技术,来个系统自带的OPcache
最近开始研究php的缓存技术,来个系统自带的OPcache php5.5以上版本 系统自带 PHP5.2-5.4 可通过扩展来安装 OPcache是 zend出品 比apc的优势在于 长期更新 ...
- Asp.Net framework 类库 自带的缓存 HttpRuntime.Cache HttpContext.Cache
两个Cache 在.NET运用中经常用到缓存(Cache)对象.有HttpContext.Current.Cache以及HttpRuntime.Cache,HttpRuntime.Cache是应用程序 ...
- ASP.NET MVC 系统过滤器、自定义过滤器
一.系统过滤器使用说明 1.OutputCache过滤器 OutputCache过滤器用于缓存你查询结果,这样可以提高用户体验,也可以减少查询次数.它有以下属性: Duration:缓存的时间,以秒为 ...
随机推荐
- netty系列之:netty初探
目录 简介 netty介绍 netty的第一个服务器 netty的第一个客户端 运行服务器和客户端 总结 简介 我们常用浏览器来访问web页面得到相关的信息,通常来说使用的都是HTTP或者HTTPS协 ...
- 浅谈vue响应式原理及发布订阅模式和观察者模式
一.Vue响应式原理 首先要了解几个概念: 数据响应式:数据模型仅仅是普通的Javascript对象,而我们修改数据时,视图会进行更新,避免了繁琐的DOM操作,提高开发效率. 双向绑定:数据改变,视图 ...
- UI_UE在线就业班(2)(Adobe Illustrator软件学习)
Adobe Illustrator软件的使用 认识AIUI_UE在线就业班(2) . ▼ AI是Adobe Illustrator的英文缩写,是Adobe公司旗下推出的一款基于矢量图形制作 ...
- for循环排它算法(经典实用)
核心代码 let lis = document.querySelectorAll("li"); for(let i = 0; i < lis.length; i ++) { ...
- DHCP\PXE+kickstart网络装机平台
DHCP概述及原理: DHCP地址分配的四次会话 DISCOVERY -****OFFER -REQUEST -ACK 服务端基本概念: 租期:允许客户机组用IP地址的时间期限,单位为秒 作用 ...
- “入职一年,那个被高薪挖来的Android开发被劝退了。”
其实,在很多小伙伴的想法中,是希望通过跳槽实现薪酬涨幅,可是跳槽不是冲动后决定,应该谨慎啊~ 01 我的学弟,最近向我吐槽,2020 年上半年入职一家公司,当时是高薪挖走的他,所谓钱到位,工作也是充满 ...
- Python3中的字符串相关操作
Python3的字符串操作相关函数详解 字符串内建函数 1. capitalize() 将字符串中的第一个字符转换成大写,其他字母变成小写.例: >>> "hello Wo ...
- linux c语言学习笔记之守护进程
哈尔滨理工大学软件工程专业08-7李万鹏原创作品,转载请标明出处 http://blog.csdn.net/woshixingaaa/archive/2010/06/06/5651095.aspx 守 ...
- SpringMVC学习05(整合ssm)
5.整合SSM 环境要求 环境: IDEA MySQL 5.7.19 Tomcat 9 Maven 3.6 要求: 需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单 ...
- 【vulhub】Weblogic CVE-2017-10271漏洞复现&&流量分析
Weblogic CVE-2017-10271 漏洞复现&&流量分析 Weblogic CVE-2017-10271 XMLDecoder反序列化 1.Weblogic-XMLDeco ...