在Core中不能使用原HttpRuntime.Cache缓存,改为MemoryCache(Microsoft.Extensions.Caching.Memory).

现MemoryCache新版为2.0.1,于原HttpRuntime.Cache扩展方法基本相同,但里面没有查询全部键(key) 的扩展,要想查询可通过反射查找

代码如下:

       public List<string> GetCacheKeys()
{
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;
}

这样我们就能获取到全部的键.

整体MemoryCacheHelper类如下:

public class MemoryCacheHelper
{
private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions()); /// <summary>
/// 验证缓存项是否存在
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public bool Exists(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return Cache.TryGetValue(key, out _);
} /// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">缓存Value</param>
/// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
/// <param name="expiressAbsoulte">绝对过期时长</param>
/// <returns></returns>
public bool Set(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value)); Cache.Set(key, value,
new MemoryCacheEntryOptions().SetSlidingExpiration(expiresSliding)
.SetAbsoluteExpiration(expiressAbsoulte));
return Exists(key);
} /// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">缓存Value</param>
/// <param name="expiresIn">缓存时长</param>
/// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
/// <returns></returns>
public bool Set(string key, object value, TimeSpan expiresIn, bool isSliding = false)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value)); Cache.Set(key, value,
isSliding
? new MemoryCacheEntryOptions().SetSlidingExpiration(expiresIn)
: new MemoryCacheEntryOptions().SetAbsoluteExpiration(expiresIn)); return Exists(key);
} #region 删除缓存 /// <summary>
/// 删除缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public void Remove(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key)); Cache.Remove(key);
} /// <summary>
/// 批量删除缓存
/// </summary>
/// <returns></returns>
public void RemoveAll(IEnumerable<string> keys)
{
if (keys == null)
throw new ArgumentNullException(nameof(keys)); keys.ToList().ForEach(item => Cache.Remove(item));
}
#endregion #region 获取缓存 /// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public T Get<T>(string key) where T : class
{
if (key == null)
throw new ArgumentNullException(nameof(key)); return Cache.Get(key) as T;
} /// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public object Get(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key)); return Cache.Get(key);
} /// <summary>
/// 获取缓存集合
/// </summary>
/// <param name="keys">缓存Key集合</param>
/// <returns></returns>
public IDictionary<string, object> GetAll(IEnumerable<string> keys)
{
if (keys == null)
throw new ArgumentNullException(nameof(keys)); var dict = new Dictionary<string, object>();
keys.ToList().ForEach(item => dict.Add(item, Cache.Get(item)));
return dict;
}
#endregion /// <summary>
/// 删除所有缓存
/// </summary>
public void RemoveCacheAll()
{
var l = GetCacheKeys();
foreach (var s in l)
{
Remove(s);
}
} /// <summary>
/// 删除匹配到的缓存
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
public void RemoveCacheRegex(string pattern)
{
IList<string> l = SearchCacheRegex(pattern);
foreach (var s in l)
{
Remove(s);
}
} /// <summary>
/// 搜索 匹配到的缓存
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
public IList<string> SearchCacheRegex(string pattern)
{
var cacheKeys = GetCacheKeys();
var l = cacheKeys.Where(k => Regex.IsMatch(k, pattern)).ToList();
return l.AsReadOnly();
} /// <summary>
/// 获取所有缓存键
/// </summary>
/// <returns></returns>
public List<string> GetCacheKeys()
{
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;
}
}

MemoryCacheHelper

Startup.cs文件public void ConfigureServices(IServiceCollection services)方法注册MemoryCache

services.AddMemoryCache();

.NET Core MemoryCache缓存获取全部缓存键的更多相关文章

  1. Redis缓存穿透和缓存雪崩的面试题解析

    前段时间去摩拜面试,然后,做笔试的时候,遇到了几道Redis面试题目,今天来做个总结.捋一下思路,顺便温习一下之前的知识,如果对您有帮助,左上角点下关注 ! 谢谢 文章目录 缓存穿透 缓存雪崩 大家都 ...

  2. Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    Go/Python/Erlang编程语言对比分析及示例   本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...

  3. .NET Core应用中使用分布式缓存及内存缓存

    .NET Core针对缓存提供了很好的支持 ,我们不仅可以选择将数据缓存在应用进程自身的内存中,还可以采用分布式的形式将缓存数据存储在一个“中心数据库”中.对于分布式缓存,.NET Core提供了针对 ...

  4. ASP.Net Core 使用Redis实现分布式缓存

    本篇我们记录的内容是怎么在Core中使用Redis 和 SQL Server 实现分布式缓存. 一.文章概念描述   分布式缓存描述: 分布式缓存重点是在分布式上,相信大家接触过的分布式有很多中,像分 ...

  5. ASP.NET Core 使用 Redis 实现分布式缓存:Docker、IDistributedCache、StackExchangeRedis

    ASP.NET Core 使用 Redis 实现分布式缓存:Docker.IDistributedCache.StackExchangeRedis 前提:一台 Linux 服务器.已安装 Docker ...

  6. ASP.NET Core中使用EasyCaching作为缓存抽象层

    ⒈是什么? 和CacheManager差不多,两者的定位和功能都差不多. EasyCaching主要提供了下面的几个功能 统一的抽象缓存接口 多种常用的缓存Provider(InMemory,Redi ...

  7. .Net Core 跨平台开发实战-服务器缓存:本地缓存、分布式缓存、自定义缓存

    .Net Core 跨平台开发实战-服务器缓存:本地缓存.分布式缓存.自定义缓存 1.概述 系统性能优化的第一步就是使用缓存!什么是缓存?缓存是一种效果,就是把数据结果存在某个介质中,下次直接重用.根 ...

  8. 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; usi ...

  9. 三大框架 之 Hibernate生成策略与缓存策略(主键生成策略、持久化、持久化类划分、一级缓存、事物管理)

    目录 Hibernate生成策略与缓存策略 主键生成策略 主键分类 主键的生成策略 持久化 什么是持久化 什么是持久化类 持久化类编写规则 持久化类的划分 三种状态区分 持久态对象特征 一级缓存 什么 ...

随机推荐

  1. 批量删除进程清理 minerd

    发现顽固minerd 进程与ntp一起启动,所以一起杀掉 yum remove ntp kill -9 `ps -ef | grep ntp|awk '{print $2}'` kill -9 `ps ...

  2. css3将图片、内容换为灰色

    直接用filter属性-webkit-filter: grayscale(100%);-moz-filter: grayscale(100%);-ms-filter: grayscale(100%); ...

  3. 支付宝SDK ios快捷支付

    配置PartnerConfig.h的参数 //合作身份者id,以2088开头的16位纯数字 #define PartnerID @"" //收款支付宝账号 #define Sell ...

  4. 【校招面试 之 C/C++】第25题 C++ 智能指针(一)之 auto_ptr

    1.智能指针背后的设计思想 我们先来看一个简单的例子: void remodel(std::string & str) { std::string * ps = new std::string ...

  5. 对于局部变量,text、ntext 和 image 数据类型无效

    开发存储过程时报如上错误.大多数人说用varchar(8000)代替text,但值我这里超过8000,不可取 解决: sql2005或以上版本支持新数据类型:varchar(max)nvarchar( ...

  6. MVC加载部分视图Partial

    加载部分视图的方法:Partial() .RenderPartial() . Action() .RenderAction() . RenderPage() partial 与 RenderParti ...

  7. js回车、ESC、F2按钮事件

    <script type="text/javascript" language=JavaScript charset="UTF-8"> docume ...

  8. 读书笔记---改善c#编程的157个建议

    1.在拼接string时,如果牵涉到其他类型,先tostring一下会减少装箱操作:频繁操作字符串变量的话,使用stringbuilder效率较高. 2.tryParse相对于parse而言效率高,t ...

  9. APScheduler 浅析

    前言 APScheduler是python下的任务调度框架,全程为Advanced Python Scheduler,是一款轻量级的Python任务调度框架.它允许你像Linux下的Crontab那样 ...

  10. linux-radhat-gitlab服务搭建

    1.安装gitlab的依赖项 sudo yum install -y curl policycoreutils-python openssh-server cronie 2.设置防火墙 sudo lo ...