循序渐进学.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 一.概述 本篇讨论如 ...
随机推荐
- SSO后期补充理解
sso系统的提出: 为什么会产生sso系统呢?它的作用是什么?这跟普通的登录系统有什么区别? 我们先来说说session的实现原理:session跟cookie都是用户的会话跟踪技术,为什么登录成功后 ...
- Openstack 网络服务 Neutron计算节点部署(十)
Neutron计算节点部署 安装组件,安装的服务器是192.168.137.12 1.安装软件包 yum install -y openstack-neutron-linuxbridge ebtabl ...
- bzoj千题计划241:bzoj3864: Hero meet devil
http://www.lydsy.com/JudgeOnline/problem.php?id=3864 题意: 给你一个DNA序列,求有多少个长度为m的DNA序列和给定序列的LCS为0,1,2... ...
- ngx_lua_API 指令详解(四)ngx.exec指令
https://github.com/openresty/lua-nginx-module#ngxexec 参照:http://blog.csdn.net/weiyuefei/article/deta ...
- HTML5 中 Geolocation 获取地理位置的原理是什么?
http://www.zhihu.com/question/20473051?sort=created geolocation的位置信息来源包括GPS.IP地址.RFID.WIFI和蓝牙的MAC地址. ...
- PHP使用数据库的并发问题
在并行系统中并发问题永远不可忽视.尽管PHP语言原生没有提供多线程机制,那并不意味着所有的操作都是线程安全的.尤其是在操作诸如订单.支付等业务系统中,更需要注意操作数据库的并发问题. 接下来我通过一个 ...
- 问题:经典类的对象明明没有__class__属性,却可以调用。
这个问题得深入python源码才能看. class a: pass aa =a() print dir(aa)#aa只有doc和module属性 print aa.__class__#__main__ ...
- 批量增加Linux系统账号、重置账号密码、FTP账号批量测试
批量增加Linux系统账号.重置账号密码是用Linux Shell脚本来做的:批量FTP账号测试是用Python脚本来做的.这些脚本都是读取一个用户名和密码文件,然后基于该用户名密码文件进行自动批量测 ...
- BurpSuite中的安全测试插件推荐
Burp Suite 是用于攻击web 应用程序的集成平台.它包含了许多工具,并为这些工具设计了许多接口,以促进加快攻击应用程序的过程.所有的工具都共享一个能处理并显示HTTP 消息,持久性,认证,代 ...
- python3迭代器和生成器
1.手动访问迭代器中的元素 #要手动访问迭代器中的元素,可以使用next()函数 In [3]: with open('/etc/passwd') as f: ...: try: ...: while ...