.NET Core 缓存使用之 MemoryCache


.NET Core 缓存使用之 MemoryCache

据时间过期的四种策略

首先说下:一般我们使用缓存都是根据时间设置过期策略的,常用的是以下四种过期策略:

1 永不过期:

永远不会过期

2 设置绝对过期时间点:

到期后就失效

3 设置过期滑动窗口:

只要在窗口期内访问,它的过期时间就一直向后顺延一个窗口长度

4 滑动窗口+绝对过期时间点:

只要在窗口期内访问,它的过期时间就一直向后顺延一个窗口长度,但最长不能超过绝对过期时间点

 

.NET Core 使用 MemoryCache 

1) 在Startup.cs 中 配置 启用缓存

C# 全选
public void ConfigureServices(IServiceCollection services)
{
	services.AddControllersWithViews();
	// 启用缓存
	services.AddMemoryCache();
}

2) 在控制器中使用 MemoryCache

C# 全选
public class WXHelperController : Controller
{
	IMemoryCache _cache;
	public WXHelperController(IMemoryCache cache)
	{
		_cache = cache;
	}
}

3) 缓存扩展方法

C# 全选
public static class GZCacheExtensions
{
	public static void GZSet<TItem>(this IMemoryCache cache, string key, TItem value, DateTime time)
	{
		cache.Set(key, value, time);
		WriteCache(key, value, time);
	}

	public static TItem GZGet<TItem>(this IMemoryCache cache, string key)
	{
		var data = cache.Get<TItem>(key);
		if (data == null)
		{
			DateTime time;
			data = GetCache<TItem>(key, out time);
			if (data != null)
			{
				cache.Set(key, data, time);
			}
		}
		return data;
	}

	static TItem GetCache<TItem>(string cacheKey, out DateTime expireTime)
	{
		string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache");
		string _filepath = System.IO.Path.Combine(filePath, cacheKey + ".cache");
		if (System.IO.File.Exists(_filepath))
		{
			try
			{
				string json = File.ReadAllText(_filepath);
				var data = Newtonsoft.Json.JsonConvert.DeserializeObject<CacheData>(json);
				expireTime = data.ExpireTime;
				if (data.ExpireTime <= DateTime.Now)
				{
					File.Delete(_filepath);
					return default(TItem);
				}

				return (data.Value as JToken).ToObject<TItem>();
			}
			catch
			{
				File.Delete(_filepath);
				expireTime = DateTime.Now;
				return default(TItem);
			}
		}
		expireTime = DateTime.Now;
		return default(TItem);
	}
	static void WriteCache<TItem>(string cacheKey, TItem value, DateTime expireTime)
	{
		string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache");
		string _filepath = System.IO.Path.Combine(filePath, cacheKey + ".cache");
		if (Directory.Exists(filePath) == false)
		{
			Directory.CreateDirectory(filePath);
		}



		//设置缓存数据的相关参数
		CacheData data = new CacheData() { Value = value, ExpireTime = expireTime };
		var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);

		Write(_filepath, json);
	}

	static void Write(string file, string content)
	{
		FileStream fs = new FileStream(file, FileMode.Create);
		//获得字节数组
		byte[] data = System.Text.Encoding.UTF8.GetBytes(content);
		//开始写入
		fs.Write(data, 0, data.Length);
		//清空缓冲区、关闭流
		fs.Flush();
		fs.Close();
	}

}

public class CacheData
{
	/// <summary>
	/// 值
	/// </summary>
	public object Value { get; set; }
	/// <summary>
	/// 到期时间
	/// </summary>
	public DateTime ExpireTime { get; set; }
}

 

其他参考代码

using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace server.Models
{
    public class CacheManager
    {

        public static CacheManager Default = new CacheManager();

        private IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions());


        /// <summary>
        /// 判断是否在缓存中
        /// </summary>
        /// <param name="key">关键字</param>
        /// <returns></returns>
        public bool IsInCache(string key)
        {
            List<string> keys = GetAllKeys();
            foreach (var i in keys)
            {
                if (i == key) return true;
            }
            return false;
        }

        /// <summary>
        /// 获取所有缓存键
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllKeys()
        {
            const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            var entries = _cache.GetType().GetField("_entries", flags).GetValue(_cache);
            var cacheItems = entries as IDictionary;
            var keys = new List<string>();
            if (cacheItems == null) return keys;
            foreach (DictionaryEntry cacheItem in cacheItems)
            {
                keys.Add(cacheItem.Key.ToString());
            }
            return keys;
        }

        /// <summary>
        /// 获取所有的缓存值
        /// </summary>
        /// <returns></returns>
        public List<T> GetAllValues<T>()
        {
            var cacheKeys = GetAllKeys();
            List<T> vals = new List<T>();
            cacheKeys.ForEach(i =>
            {
                T t;
                if (_cache.TryGetValue<T>(i, out t))
                {
                    vals.Add(t);
                }
            });
            return vals;
        }
        /// <summary>
        /// 取得缓存数据
        /// </summary>
        /// <typeparam name="T">类型值</typeparam>
        /// <param name="key">关键字</param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));
            T value;
            _cache.TryGetValue<T>(key, out value);
            return value;
        }

        /// <summary>
        /// 设置缓存(永不过期)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_NotExpire<T>(string key, T value)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_cache.TryGetValue(key, out v))
                _cache.Remove(key);
            _cache.Set(key, value);
        }

        /// <summary>
        /// 设置缓存(滑动过期:超过一段时间不访问就会过期,一直访问就一直不过期)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_SlidingExpire<T>(string key, T value, TimeSpan span)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_cache.TryGetValue(key, out v))
                _cache.Remove(key);
            _cache.Set(key, value, new MemoryCacheEntryOptions()
            {
                SlidingExpiration = span
            });
        }

        /// <summary>
        /// 设置缓存(绝对时间过期:从缓存开始持续指定的时间段后就过期,无论有没有持续的访问)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_AbsoluteExpire<T>(string key, T value, TimeSpan span)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_cache.TryGetValue(key, out v))
                _cache.Remove(key);
            _cache.Set(key, value, span);
        }

        /// <summary>
        /// 设置缓存(绝对时间过期+滑动过期:比如滑动过期设置半小时,绝对过期时间设置2个小时,那么缓存开始后只要半小时内没有访问就会立马过期,如果半小时内有访问就会向后顺延半小时,但最多只能缓存2个小时)
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="value">缓存值</param>
        public void Set_SlidingAndAbsoluteExpire<T>(string key, T value, TimeSpan slidingSpan, TimeSpan absoluteSpan)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            T v;
            if (_cache.TryGetValue(key, out v))
                _cache.Remove(key);
            _cache.Set(key, value, new MemoryCacheEntryOptions()
            {
                SlidingExpiration = slidingSpan,
                AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(absoluteSpan.Milliseconds)
            });
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="key">关键字</param>
        public void Remove(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            _cache.Remove(key);
        }

        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
            if (_cache != null)
                _cache.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
GarsonZhang www.yesdotnet.com

 

参考地址: https://blog.csdn.net/u010476739/article/details/102947433

 

 

版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
管理员
上一篇:.NET MVC加载从后台加载JS代码块
下一篇:less里面calc() 语法使用
评论列表

发表评论

评论内容
昵称:
验证码:
验证码
关联文章

.NET Core 缓存使用 MemoryCache
MemoryCache 如何清除全部缓存
.NET Core ResponseCache 浏览器缓存
使用.NET 6开发TodoList应用(22)——实现缓存
ASP.NET Core 使用 LESS
.net core使用Microsoft.Data.Sqlite创建SQLite数据库文件
.NET Core MVC中间件使用记录日志
.net core MVC 使用 jquery ajax请求 Post json
.net 微服务RFC
.NET Core 运行时T4模板使用,T4生成代码
在ASP.NET Core web API中使用Swagger/OpenAPI(Swashbuckle)
熔断和降级的初步详解实现(NET Core控制台输出讲解Polly)
ASP.NET Core官网教程,资料查找
ASP.NET Core开发者学习路线图
.NET Core 项目 DbProviderFactories.GetFactoryClasses()返回空
.NET Core使用编码GB2312报错‘GB2312‘ is not a supported encoding name 解决方案
C# ASP.NET Core开发学生信息管理系统(一)
【推荐】Razor文件编译 ASP.NET Core
使用 .NET Core 和 Quartz.NET 实现任务调度持久化:更相信配置任务调度
C# ASP.NET Core开发学生信息管理系统(三)

热门标签
.NET Core .NET Reactor ag-grid AI发布 api安全 ASP.NET Core C#DLL加密 C#播放声音 C#代码混淆 C#代码加密 ChromeDriver Codex DateTime DBeaver devexpress devTool DLL混淆 edge.js EF EFCore Electron element-ui el-form el-table excel FastReport FileStream FolderBrowerDialog FolderSelectDialog form提交 git gridcontrol gridview input javascript json字符串 JS转换对象JSON jwt JWT授权 linq log Math MCP mitmproxy MVC MySQL Navicat netstat nginx node_modules NSwag Nuget Nuget镜像 number PowerShell pyinstaller python pythoncom python爬虫 python抓包 pywin32 redis Requests-html RestSharp Selenium sql SQL Server Swagger to-cms Visual Studio VSCode vue VueRouter vue路由 VUE页面通讯 Webpack Windows Windows服务 winform wmi xlrd yaml YESCMS YESWEB开发框架 白象 表单提交 播放声音 打开URL 代码混淆 弹窗提醒 端口占用 对象转换 分布式 公共字典 机器码 进程排查 静态资源 开发指南 路由参数 密钥 配置教程 配置文件 权限 人工智能 任务 任务调度 日期间隔 日志 日志记录 省市区 授权验证 数据库 四舍五入 文案 文件读取 文件夹选择 文件目录选择 问题排查 行政区域数据 页面通讯 中间件 CSharp 事务锁 工单系统 并发控制 重复提交 CMS Markdig Markdown markdown-it marked 技术选型 VS Code 开发工具 源代码管理 版本控制 Docker PostgreSQL 时区 部署排查 CMS架构 EF Core 主题系统 二次开发 插件系统 容器 运维命令 镜像清理 Linux NAS 远程挂载 飞牛 fnOS S/4HANA SAP GUI SAP HANA SAP R/3 SAP入门 SAP版本 ERP SAP SAP MM 库存管理 物料管理 采购管理 入门教程 SAP S/4HANA SPRO 企业结构 采购组织 MM01 物料主数据 物料类型 BP分组 业务伙伴 供应商主数据 ME41 RFQ 库存物料 采购流程 ME51 消耗性物料 科目分配 采购申请 AC03 ML81N 外部服务 服务主数据 Business Partner SAP培训
联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码