系列目录

循序渐进学.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. 位运算的一种应用 和 hiho1516过河解题报告

    初始i=s 每次:i=(i-1) & s 直到i=0 etc.11000100000100000000 10000=10001 & 1100001000=01111 & 110 ...

  2. Excel:公式应用技巧汇总

    1.合并单元格添加序号:=MAX(A$1:A1)+1 不重复的个数: 公式1:{=SUM(1/COUNTIF(A2:A8,A2:A8))} 公式2:{=SUM(--(MATCH(A2:A8,A2:A8 ...

  3. C# 基于MySQL的数据层基类(MySQLHelper)

    这里介绍下比较简单的方式,引用MySql.Data.dll然后添加一个MySqlHelper类来对MySql数据库进行访问和操作. 1.将MySql.Data.dll引用到你的项目中 下载地址:MyS ...

  4. java基础基础总结----- StringBuffer(重要)

    前言StringBuffer:(常用的方法) StringBuffer与StringBuilder的区别 关于安全与不安全的解释:

  5. Flask script 内的Shell 类 使用

    1.集成Python shell 每次自动shell会话都要导入数据库实例和模型,很烦人.为了避免一直重复导入,我们可以做些配置让Flask-Script的Shell命令自动导入特定的对象.若想把对象 ...

  6. How To Crawl A Web Page with Scrapy and Python 3

    sklearn实战-乳腺癌细胞数据挖掘(博主亲自录制视频) https://study.163.com/course/introduction.htm?courseId=1005269003& ...

  7. list里面放的实体对象,页面用c:foreach应该怎么取?

    关于网友提出的" list里面放的实体对象,页面用c:foreach应该怎么取?"问题疑问,本网通过在网上对" list里面放的实体对象,页面用c:foreach应该怎么 ...

  8. 使用mybatisgenerator 辅助工具逆向工程

    使用mybatisgenerator 辅助工具生成单表的dao层接口,mapper xml 文件以及实体类,复杂的还得人手动去编写哈...所以我也不觉得这玩意儿在项目简单情况下有什么鸟用... wha ...

  9. 公告:关注canvas的同学注意了

    因为我之前把基础大致都帮各位详细讲过了! 什么fill,line,乱七八糟的一堆.都有demo了 所以我最近写起来可能会快很多了!如果有不明白的只能请各位回顾下之前的文章了 毕竟如果按照这个进度写文章 ...

  10. svn使用笔记

    一.checkout:第一次下载trunk里面的代码到本地 二.commit:提交一些修改* out of date : 本地版本号 < 服务器版本号* 如果过期,就update,可能会出现co ...