系列目录

循序渐进学.Net Core Web Api开发系列目录

本系列涉及到的源码下载地址: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】:缓存的更多相关文章

  1. 循序渐进学.Net Core Web Api开发系列【0】:序言与目录

    一.序言 我大约在2003年时候开始接触到.NET,最初在.NET framework 1.1版本下写过代码,曾经做过WinForm和ASP.NET开发.大约在2010年的时候转型JAVA环境,这么多 ...

  2. 循序渐进学.Net Core Web Api开发系列【16】:应用安全续-加密与解密

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 应用安全除 ...

  3. 循序渐进学.Net Core Web Api开发系列【15】:应用安全

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍W ...

  4. 循序渐进学.Net Core Web Api开发系列【14】:异常处理

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍异 ...

  5. 循序渐进学.Net Core Web Api开发系列【13】:中间件(Middleware)

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  6. 循序渐进学.Net Core Web Api开发系列【11】:依赖注入

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  7. 循序渐进学.Net Core Web Api开发系列【10】:使用日志

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.本篇概述 本篇介 ...

  8. 循序渐进学.Net Core Web Api开发系列【9】:常用的数据库操作

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇描述一 ...

  9. 循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇讨论如 ...

随机推荐

  1. HDU 6158 笛卡尔定理+韦达定理

    The Designer Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Tota ...

  2. 形参与实参的区别---java基础

    1.形参变量只有在被调用时才分配内存单元,在调用结束时,即刻释放所分配的内存单元.因此,形参只在函数内部有效.函数调用结束返回主调用函数后则不能再使用该形参变量.2.实参可以是常量.变量.表达式.函数 ...

  3. duilib踩坑记录

    duilib官方 https://github.com/duilib/duilib duilib他人扩展 https://github.com/qdtroy/DuiLib_Ultimate 关于两者的 ...

  4. CXF wsdl2java 生成java代码供客户端使用

    CXF wsdl2java 生成java代码供客户端使用 环境配置:1.下载apache-cxf-2.6.2在环境变量中配置CXF_HOME 值为E:\gavin\cxf\apache-cxf-3.0 ...

  5. JIRA项目管理搭建

    部署JIRA 7.2.2 for Linux 转自:http://www.yfshare.vip/2017/05/09/%E9%83%A8%E7%BD%B2JIRA-7-2-2-for-Linux/ ...

  6. Win10新增功能快捷键大全

    原文地址:http://wenwen.sogou.com/z/q703976788.htm贴靠窗口:Win + 左/右 > Win + 上/下 > 窗口可以变为 1/4 大小放置在屏幕 4 ...

  7. Windows系统安装————windows7 企业版 无法安装 NET.framework4.52-4.6版本在WIN7下解决办法

    官方安装包下载地址:https://www.microsoft.com/zh-cn/download/details.aspx?id=48137 我安装了NMM后提示NET.framework版本太低 ...

  8. mysql复杂查询(一)

    所谓复杂查询,指涉及多个表.具有嵌套等复杂结构的查询.这里简要介绍典型的几种复杂查询格式. 一.连接查询 连接是区别关系与非关系系统的最重要的标志.通过连接运算符可以实现多个表查询.连接查询主要包括内 ...

  9. o(1), o(n), o(logn), o(nlogn)算法复杂度

    在描述算法复杂度时,经常用到o(1), o(n), o(logn), o(nlogn)来表示对应算法的时间复杂度, 这里进行归纳一下它们代表的含义: 这是算法的时空复杂度的表示.不仅仅用于表示时间复杂 ...

  10. TCP/UDP区别&&心跳包机制【转】

    转自:https://www.jianshu.com/p/6d93a3c21c34 UDP:用户数据报协议:主要用在实时性要求比较高的以及对质量相对较弱的地方.但是面对现在高质量的线路不会容易丢包,除 ...