NetCore的缓存使用详例

关于我

作者博客|文章首发

缓存基础知识

缓存可以减少生成内容所需的工作,从而显著提高应用程序的性能和可伸缩性。 缓存最适用于不经常更改的 数据,生成 成本很高。 通过缓存,可以比从数据源返回的数据的副本速度快得多。 应该对应用进行编写和测试,使其 永不 依赖于缓存的数据。

ASP.NET Core 支持多个不同的缓存。 最简单的缓存基于 IMemoryCache。 IMemoryCache 表示存储在 web 服务器的内存中的缓存。 在服务器场上运行的应用 (多台服务器) 应确保会话在使用内存中缓存时处于粘滞状态。 粘滞会话确保来自客户端的后续请求都将发送到相同的服务器。

内存中缓存可以存储任何对象。 分布式缓存接口仅限 byte[] 。 内存中和分布式缓存将缓存项作为键值对。

缓存指南

  • 代码应始终具有回退选项,以获取数据,而 是依赖于可用的缓存值。
  • 缓存使用稀有资源内存,限制缓存增长:
    • 不要 使用外部 输入作为缓存键。
    • 使用过期限制缓存增长。
    • 使用 SetSize、Size 和 SizeLimit 限制缓存大小]。 ASP.NET Core 运行时不会根据内存 压力限制缓存 大小。 开发人员需要限制缓存大小。

使用

DI注入

创建一个NetCore控制台项目,进行缓存的项目演示。

控制台项目只有一个初始化的Program.cs文件。基于NetCore进行项目编码,每一步就是创建一个基础模板,使用依赖注入的方式。

nuget install Microsoft.Extensions.Hosting
1 public static class Program 2 { 3 static async void Main(string[] args) 4 { 5 var builder = new HostBuilder().ConfigureServices((context, service) => 6 { 7 8 }); 9 10 await builder.RunConsoleAsync(); 11 } 12 }

注入缓存服务,控制台需要下载库 Microsoft.Extensions.Caching.Memory

nuget install Microsoft.Extensions.Caching.Memory
1 public static class Program 2 { 3 static async void Main(string[] args) 4 { 5 var builder = new HostBuilder().ConfigureServices((context, service) => 6 { 7 service.AddMemoryCache(); 8 9 service.AddScoped<CacheService>();//实际测试服务 10 11 service.AddHostedService<BackgroundJob>();//后台执行方法 12 }); 13 14 await builder.RunConsoleAsync(); 15 } 16 }

后台服务

1public class BackgroundJob : IHostedService 2 { 3 private readonly CacheService _cacheService; 4 5 public BackgroundJob(CacheService cacheService) 6 { 7 _cacheService = cacheService; 8 } 9 10 public Task StartAsync(CancellationToken cancellationToken) 11 { 12 _cacheService.Action(); 13 14 return Task.CompletedTask; 15 } 16 17 public Task StopAsync(CancellationToken cancellationToken) 18 { 19 return Task.CompletedTask; 20 } 21 }

MemoryCache使用总结

通过构造函数自动注入IMemoryCache

1public class CacheService 2{ 3 private readonly IMemoryCache _memoryCache; 4 5 public CacheService(IMemoryCache memoryCache) 6 { 7 _memoryCache = memoryCache; 8 } 9}

最基本的使用

Set方法根据Key设置缓存,默认缓存不过期

Get方法根据Key取出缓存

1/// <summary> 2/// 缓存设置 3/// </summary> 4public void BaseCache() 5{ 6 string cacheKey = "timestamp"; 7 //set cache 8 _memoryCache.Set(cacheKey, DateTime.Now.ToString()); 9 10 //get cache 11 Console.WriteLine(_memoryCache.Get(cacheKey)); 12}

IMemoryCache提供一些好的语法糖供开发者使用,具体内容看下方文档

1/// <summary> 2/// 特殊方法的使用 3/// </summary> 4public void ActionUse() 5{ 6 //场景-如果缓存存在,取出。如果缓存不存在,写入 7 //原始写法 8 string cacheKey = "timestamp"; 9 if (_memoryCache.Get(cacheKey) != null) 10 { 11 _memoryCache.Set(cacheKey, DateTime.Now.ToString()); 12 } 13 else 14 { 15 Console.WriteLine(_memoryCache.Get(cacheKey)); 16 } 17 18 //新写法 19 var dataCacheValue = _memoryCache.GetOrCreate(cacheKey, entry => 20 { 21 return DateTime.Now.ToString(); 22 }); 23 Console.WriteLine(dataCacheValue); 24 25 //删除缓存 26 _memoryCache.Remove(cacheKey); 27 28 //场景 判断缓存是否存在的同时取出缓存数据 29 _memoryCache.TryGetValue(cacheKey, out string cacheValue); 30 Console.WriteLine(cacheValue); 31 32}

缓存过期策略

设置缓存常用的方式主要是以下二种

  1. 绝对到期(指定在一个固定的时间点到期)
  2. 滑动到期(在一个时间长度内没有被命中则过期)
  3. 组合过期 (绝对过期+滑动过期)

绝对到期

过期策略 5秒后过期

1//set absolute cache 2string cacheKey = "absoluteKey"; 3_memoryCache.Set(cacheKey, DateTime.Now.ToString(), TimeSpan.FromSeconds(5)); 4 5//get absolute cache 6for (int i = 0; i < 6; i++) 7{ 8 Console.WriteLine(_memoryCache.Get(cacheKey)); 9 Thread.Sleep(1000); 10}

滑动到期

过期策略 2秒的滑动过期时间,如果2秒内有访问,过期时间延后。当2秒的区间内没有访问,缓存过期

1//set slibing cache 2string cacheSlibingKey = "slibingKey"; 3MemoryCacheEntryOptions options = new MemoryCacheEntryOptions(); 4options.SlidingExpiration = TimeSpan.FromSeconds(2); 5 6_memoryCache.Set(cacheSlibingKey, DateTime.Now.ToString(), options); 7 8//get slibing cache 9for (int i = 0; i < 2; i++) 10{ 11 Console.WriteLine(_memoryCache.Get(cacheSlibingKey)); 12 Thread.Sleep(1000); 13} 14for (int i = 0; i < 2; i++) 15{ 16 Thread.Sleep(2000); 17 Console.WriteLine(_memoryCache.Get(cacheSlibingKey)); 18}

组合过期

过期策略

6秒绝对过期+2秒滑动过期

满足任意一个缓存都将失效

1string cacheCombineKey = "combineKey"; 2MemoryCacheEntryOptions combineOptions = new MemoryCacheEntryOptions(); 3combineOptions.SlidingExpiration = TimeSpan.FromSeconds(2); 4combineOptions.AbsoluteExpiration = DateTime.Now.AddSeconds(6); 5 6_memoryCache.Set(cacheCombineKey, DateTime.Now.ToString(), combineOptions); 7 8//get slibing cache 9for (int i = 0; i < 2; i++) 10{ 11 Console.WriteLine(_memoryCache.Get(cacheCombineKey)); 12 Thread.Sleep(1000); 13} 14 15for (int i = 0; i < 6; i++) 16{ 17 Thread.Sleep(2000); 18 Console.WriteLine(i+"|" + _memoryCache.Get(cacheCombineKey)); 19} 20 21Console.WriteLine("------------combineKey End----------------");

缓存状态变化事件

当缓存更新、删除时触发一个回调事件,记录缓存变化的内容。

1/// <summary> 2/// cache状态变化回调 3/// </summary> 4public void CacheStateCallback() 5{ 6 MemoryCacheEntryOptions options = new MemoryCacheEntryOptions(); 7 options.AbsoluteExpiration = DateTime.Now.AddSeconds(3 8 ); 9 options.RegisterPostEvictionCallback(MyCallback, this); 10 11 //show callback console 12 string cacheKey = "absoluteKey"; 13 _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options); 14 15 Thread.Sleep(500); 16 _memoryCache.Set(cacheKey, DateTime.Now.ToString(), options); 17 18 _memoryCache.Remove(cacheKey); 19 20} 21 22private static void MyCallback(object key, object value, EvictionReason reason, object state) 23{ 24 var message = $"Cache entry state change:{key} {value} {reason} {state}"; 25 ((CacheService)state)._memoryCache.Set("callbackMessage", message); 26 27 Console.WriteLine(message); 28}

缓存依赖策略

设置一个缓存A 设置一个缓存B,依赖于缓存A 如果缓存A失效,缓存B也失效

1/// <summary> 2/// 缓存依赖策略 3/// </summary> 4public void CacheDependencyPolicy() 5{ 6 string DependentCTS = "DependentCTS"; 7 string cacheKeyParent = "CacheKeys.Parent"; 8 string cacheKeyChild = "CacheKeys.Child"; 9 10 var cts = new CancellationTokenSource(); 11 _memoryCache.Set(DependentCTS, cts); 12 13 //创建一个cache策略 14 using (var entry = _memoryCache.CreateEntry(cacheKeyParent)) 15 { 16 //当前key对应的值 17 entry.Value = "parent" + DateTime.Now; 18 19 //当前key对应的回调事件 20 entry.RegisterPostEvictionCallback(MyCallback, this); 21 22 //基于些key创建一个依赖缓存 23 _memoryCache.Set(cacheKeyChild, "child" + DateTime.Now, new CancellationChangeToken(cts.Token)); 24 } 25 26 string ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent); 27 string ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild); 28 string callBackMsg = _memoryCache.Get<string>("callbackMessage"); 29 Console.WriteLine("第一次获取"); 30 Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg); 31 32 //移除parentKey 33 _memoryCache.Get<CancellationTokenSource>(DependentCTS).Cancel(); 34 Thread.Sleep(1000); 35 36 ParentCachedTime = _memoryCache.Get<string>(cacheKeyParent); 37 ChildCachedTime = _memoryCache.Get<string>(cacheKeyChild); 38 callBackMsg = _memoryCache.Get<string>("callbackMessage"); 39 Console.WriteLine("第二次获取"); 40 Console.WriteLine(ParentCachedTime + "|" + ChildCachedTime + "|" + callBackMsg); 41}

参考资料

AspNetCore中的缓存内存

.NetCore缓存篇之MemoryCache

Asp.Net Core 轻松学-在.Net Core 使用缓存和配置依赖策略

拥抱.NET Core系列:MemoryCache 缓存过期

推荐阅读

Redis工具收费后新的开源已出现

GitHub上Star最高的工程师技能图谱

中国程序员最容易发错的单词

推荐!!! Markdown图标索引网站

最后

本文到此结束,希望对你有帮助 😃

如果还有什么疑问或者建议,可以多多交流,原创文章,文笔有限,才疏学浅,文中若有不正之处,万望告知。

更多精彩技术文章汇总在我的 公众号【程序员工具集】,持续更新,欢迎关注订阅收藏。

wechat.png

点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

前端性能优化 - 雅虎军规

无论是在工作中,还是在面试中,web前端性能的优化都是很重要的,那么我们进行优化需要从哪些方面入手呢?可以遵循雅虎的前端优化35条军规,这样对于优化有一个比较清晰的方向.35条军规1.尽量减少HTTP请求个数——须权衡2.使用CDN(内容分发网络)3.为文件头指定Expires或CacheControl,使内容具有缓存性。4.避免空的

J2Cache 没有 Redis 也可以实现多节点的缓存同步

J2Cache是一个两级的缓存框架,第一级是基于内存的数据缓存,支持caffeine、ehcache2和ehcache3,二级缓存只支持redis。在某些生产环境中你可能没有redis,但是又希望多个应用节点间的缓存数据是同步的。配置的方法很简单:1\.首先关闭二级缓存(使用none替代redis)j2cache

Hibernate 缓存机制

一、为什么要用Hibernate缓存Hibernate是一个持久层框架,经常访问物理数据库。为了降低应用程序对物理数据源访问的频次,从而提高应用程序的运行性能。缓存内的数据是对物理数据源中的数据的复制,应用程序在运行时从缓存读写数据,在特定的时刻或事件会同步缓存和物理数据源的数据。二、Hibernate

MemCache 入门极简教程

MemCache概述MemCache虽然被称为”分布式缓存”,但是MemCache本身完全不具备分布式的功能Memcache是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高了网站访问的速度。MemCaChe是一个存储键值对的Hash

Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

MemcachedMemcached是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap(https://www.oschina.net/action/GoToLin