循序渐进学.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 一.概述 本篇讨论如 ...
随机推荐
- C#利用Zxing.net生成条形码和二维码并实现打印的功能
开篇:zxing.net是.net平台下编解条形码和二维码的工具. 下载地址:http://pan.baidu.com/s/1kTr3Vuf Step1:使用VS2010新建一个窗体程序项目: ...
- NameError: name 'reload' is not defined
对于 Python 2.X: import sys reload(sys) sys.setdefaultencoding("utf-8") 对于 <= Python 3.3: ...
- Mac OS利用ssh访问ubuntu虚拟机及云端操作
1.桥接模式 将该虚拟机的网口设置成桥接模式(Bridged Adapter),以确保主机可以ping通虚拟机: 2.安装ssh 在ubuntu虚拟机上安装ssh server: sudo apt-g ...
- 第一篇:打造专属开发工具Eclipse篇
第一篇:打造专属开发工具Eclipse篇 eclipse 优化 1.动画很酷,但如果可以的话,我总是在所有的工具中禁用动画.所以classic或者window classic主题是我最常用的主题 , ...
- python---django使用cookie和session
在views中的调用: def login(req): message='' if req.method == "POST": user = req.POST.get(" ...
- bzoj千题计划277:bzoj4513: [Sdoi2016]储能表
http://www.lydsy.com/JudgeOnline/problem.php?id=4513 f[i][0/1][0/1][0/1] 从高到低第i位,是否卡n的上限,是否卡m的上限,是否卡 ...
- [整理]Assembly中的DLL提取
当机器上安装一些程序后,Assembly中的DLL会变得越来越丰富. 拿个常见问题来说明. 安装ReportViewer后其中会出现以下DLL. Microsoft.ReportViewer.Proc ...
- 阿里云OSS 中文名称地址不对
oss中将该中文名称重命名.再输入一次
- input文本框禁止修改文本——disabled和readonly属性的作用及区别
1.input文本框禁止修改文本 disabled属性:<input type="text" name="name" value="xxx&qu ...
- Linux 内核中断内幕【转】
转自:http://www.ibm.com/developerworks/cn/linux/l-cn-linuxkernelint/ 本文对中断系统进行了全面的分析与探讨,主要包括中断控制器.中断分类 ...