循序渐进学.Net Core Web Api开发系列【12】:缓存
系列目录
本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi
一、概述
本篇介绍如何使用缓存,包括MemeryCache和Redis。
二、MemeryCache
1、注册缓存服务
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
}
貌似较新的版本是默认已经注册缓存服务的,以上代码可以省略,不过加一下也没有问题。
2、在Controller中注入依赖
public class ArticleController : Controller
{
private readonly IMemoryCache _cache; public ArticleController(SalesContext context, ILogger<ArticleController> logger, IMemoryCache memoryCache)
{
_cache = memoryCache;
}
}
3、基本使用方法
public List<Article> GetAllArticles()
{
List<Article> articles = null; if (!_cache.TryGetValue<List<Article>>("GetAllArticles", out articles))
{
_logger.LogInformation("未找到缓存,去数据库查询"); articles = _context.Articles
.AsNoTracking()
.ToList<Article>(); _cache.Set("GetAllArticles", articles);
} return articles;
}
逻辑是这样的:
(1)、去缓存读取指定内容;(2)如果没有读取到,就去数据库区数据,并存入缓存;(3)如果取到就直接返回数据。
4、缓存的过期
绝对过期:设定时间一到就过期。适合要定期更新的场景,比如组织机构信息数据。
_cache.Set("GetAllArticles", articles,
new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds()));
相对过期:距离最后一次使用(TryGetValue)后指定时间后过期,比如用户登陆信息。
_cache.Set("GetAllArticles", articles,
new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds()));
三、分布式缓存Redis的使用
1、缓存服务注册
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedRedisCache(options =>
{
options.Configuration = Configuration["Redis:Configuration"];
options.InstanceName = Configuration["Redis:InstanceName"];
});
}
appsettings.json的内容大致如下:
{
"ConnectionStrings": {
"SQLServerConnection": "....;",
"MySQLConnection": "...;"
},
"Redis": {
"Configuration": "IP:1987,allowAdmin=true,password=******,defaultdatabase=5",
"InstanceName": "SaleService_"
}
}
如果设置了的InstanceName话,所有存储的KEY会增加这个前缀。
2、在Controller中引入依赖
[Produces("application/json")]
[Route("api/Article")]
public class ArticleController : Controller
{ private readonly IDistributedCache _distributedCache;
public ArticleController(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
}
3、基本使用
[HttpGet("redis")]
public void TestRedis()
{
String tockenid = "AAAaaa";
string infostr = _distributedCache.GetString(tockenid);
if(infostr == null)
{
_logger.LogInformation("未找到缓存,写入Redis");
_distributedCache.SetString(tockenid, "hello,0601");
}
else
{
_logger.LogInformation("找到缓存");
_logger.LogInformation($"infostr={infostr}");
}
return;
}
}
4、存储对象
由于Redis只能存储字符串,所有对于对象的存取需要进行序列化操作。
[HttpGet("redis_object")]
public List<Article> TestRedis4Object()
{
String objectid = "articles";
List<Article> articles = null;
var valuebytes = _distributedCache.Get(objectid);
if (valuebytes == null)
{
_logger.LogInformation("未找到缓存,写入Redis");
articles = _context.Articles.AsNoTracking().ToList();
byte[] serializedResult = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(articles));
_distributedCache.Set(objectid, serializedResult);
return articles;
}
else
{
_logger.LogInformation("找到缓存");
articles =JsonConvert.DeserializeObject<List<Article>>(Encoding.UTF8.GetString(valuebytes));
return articles;
}
}
5、缓存的过期
绝对过期:
_distributedCache.SetString(tockenid, "hello,0601",new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds()));
相对过期:
_distributedCache.SetString(tockenid, "hello,0601",new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds()));
6、客户端工具
采用Redis Desktop Manager 可以查看存储情况

循序渐进学.Net Core Web Api开发系列【12】:缓存的更多相关文章
- 循序渐进学.Net Core Web Api开发系列【0】:序言与目录
一.序言 我大约在2003年时候开始接触到.NET,最初在.NET framework 1.1版本下写过代码,曾经做过WinForm和ASP.NET开发.大约在2010年的时候转型JAVA环境,这么多 ...
- 循序渐进学.Net Core Web Api开发系列【16】:应用安全续-加密与解密
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 应用安全除 ...
- 循序渐进学.Net Core Web Api开发系列【15】:应用安全
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍W ...
- 循序渐进学.Net Core Web Api开发系列【14】:异常处理
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍异 ...
- 循序渐进学.Net Core Web Api开发系列【13】:中间件(Middleware)
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...
- 循序渐进学.Net Core Web Api开发系列【11】:依赖注入
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...
- 循序渐进学.Net Core Web Api开发系列【10】:使用日志
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.本篇概述 本篇介 ...
- 循序渐进学.Net Core Web Api开发系列【9】:常用的数据库操作
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇描述一 ...
- 循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇讨论如 ...
随机推荐
- jq给单选框 radio添加或删除选中状态
$("#div1 :radio").removeAttr("checked");//删除目标div下所有单选框的选中状态 $("#div1 :radi ...
- lrzsz 移植到 ARM-linux 嵌入式板子上
特别说明:SSH 或 串口 都可以使用 lrzsz 进行通信 lrzsz是一个Unix通信包,提供XMODEM.YMODEM和ZMODEM文件传输协议.lrzsz以前是Omen科技的主打软件,现在已经 ...
- 国内k8s集群部署的几种方式
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/lusyoe/article/details/80217291前言总所周知,由于某种原因,通过官方的方 ...
- Java基础-IO流对象之压缩流(ZipOutputStream)与解压缩流(ZipInputStream)
Java基础-IO流对象之压缩流(ZipOutputStream)与解压缩流(ZipInputStream) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 之前我已经分享过很多的J ...
- freemark+ITextRenderer 生成PDF,设置pdf的页面大小
在html中添加样式,仅生成pdf是生效,浏览器展示时是不会生效的: <style> @page{ size : 200mm 300 mm; } </style>
- Splay模板讲解及一些题目
普通平衡树模板以及文艺平衡树模板链接. 简介 平衡二叉树(Balanced Binary Tree)具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二 ...
- JavaScript继承详解(三)
在第一章中,我们使用构造函数和原型的方式在JavaScript的世界中实现了类和继承, 但是存在很多问题.这一章我们将会逐一分析这些问题,并给出解决方案. 注:本章中的jClass的实现参考了Simp ...
- 20155212 2016-2017-2 《Java程序设计》第8周学习总结
20155212 2016-2017-2 <Java程序设计>第8周学习总结 教材学习内容总结 Chapter14 1. Channel架构与操作 想要取得Channel的实作对象,可以使 ...
- TCP长连接和短连接的区别【转】
转自:https://www.cnblogs.com/onlysun/p/4520553.html 当网络通信时采用TCP协议时,在真正的读写操作之前,server与client之间必须建立一个连接, ...
- linux驱动---等待队列、工作队列、Tasklets【转】
转自:https://blog.csdn.net/ezimu/article/details/54851148 概述: 等待队列.工作队列.Tasklet都是linux驱动很重要的API,下面主要从用 ...