ASP.NET Core 使用 Redis 实现分布式缓存:Docker、IDistributedCache、StackExchangeRedis

前提:一台 Linux 服务器、已安装 Docker。

一,Docker 中运行 Redis

拉取 Redis 镜像

docker pull redis

查询镜像列表

docker imgaes

运行 Redis的几种方法

①运行并且设置 Redis 端口

docker run -p 6379:6379 -d redis:latest redis-server

docker run -p 6379:6379 -d {镜像id} redis-server

③持久化

将 Docker 里的 Redis 数据持久化到物理机

docker run -p 6379:6379 -v {物理机路径}:/data  -d redis:latest redis-server --appendonly yes

下载 Windows 版的 Redis 管理器

Windows 版本的 Redis Desktop Manager 64位 2019.1(中文版) 下载地址 https://www.7down.com/soft/233274.html

官方正版最新版本下载地址 https://redisdesktop.com/download

另附 Redis 学习教程:

Redis 中文网 https://www.redis.net.cn/

.NET 使用 Redis 学习 地址(貌似这个教程版本过时了) https://www.cnblogs.com/cang12138/p/8884362.html

搭建 Master/Slaver 模式的 Redis 集群 https://blog.csdn.net/lupengfei1009/article/details/88323561#_154

使用 Redis Desktop Manager 连接 Redis

二,ASP.NET Core 使用分布式缓存

ASP.NET Core 中,支持使用多种数据库进行缓存,ASP.NET Core 提供了统一的接口给开发者使用。

IDistributedCache

ASP.NET Core 中,使用 IDistributedCache 为开发者提供统一的缓存使用接口,而不必关注使用的是何种数据库。

IDistributedCache]接口提供了以下方法操作的分布式的缓存实现中的项:

  • GetAsync –接受字符串键和检索缓存的项作为byte[]数组如果在缓存中找到。
  • SetAsync –中添加项 (作为byte[]数组) 到使用字符串键的缓存。
  • RefreshAsync –刷新缓存基于其密钥,重置其滑动到期超时值 (如果有) 中的项。
  • RemoveAsync –移除缓存项根据其字符串键值。

IDistributedCache 提供的常用方法如下:

方法 说明
Get(String) 获取Key(键)的值
GetAsync(String, CancellationToken) 异步获取键的值
Refresh(String) 刷新缓存
RefreshAsync(String, CancellationToken) Refreshes a value in the cache based on its key, resetting its sliding expiration timeout (if any).
Remove(String) 移除某个值
RemoveAsync(String, CancellationToken) Removes the value with the given key.
[Set(String, Byte], DistributedCacheEntryOptions) Sets a value with the given key.
[SetAsync(String, Byte], DistributedCacheEntryOptions, CancellationToken) Sets the value with the given key.

官方文档很详细https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache?view=aspnetcore-2.2

ASP.NET Core 中配置缓存

新建一个 ASP.NET Core WebApi 项目

Nuget 管理器安装

Microsoft.Extensions.Caching.StackExchangeRedis

ConfigureServices 中使用服务

services.AddDistributedMemoryCache();

配置 Redis 服务器

            services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
options.InstanceName = "mvc";
});

InstanceName 是你自定义的实例名称,创建缓存时会以此名称开头。

这样就配置好了。

使用缓存

修改默认生成的 ValuesController.cs。

注入缓存服务

        private readonly IDistributedCache _cache;
public ValuesController(IDistributedCache cache)
{
_cache = cache;
}

设置缓存和使用缓存:

await _cache.GetAsync("{键名}");
_cache.SetAsync("键名", {值}, {设置});

删除原来的方法,添加以下代码:

        [HttpGet("Set")]
public async Task<JsonResult> SetCache(string setkey, string setvalue)
{ string key = "key1";
if (!string.IsNullOrEmpty(setkey))
key = setkey;
string value = DateTime.Now.ToLongTimeString();
if (!string.IsNullOrEmpty(setvalue))
value = setvalue;
await _cache.SetStringAsync(key, value);
return new JsonResult(new { Code = 200, Message = "设置缓存成功", Data = "key=" + key + " value=" + value });
} [HttpGet("Get")]
public async Task<JsonResult> GetCache(string setkey)
{
string key = "key1";
if (!string.IsNullOrEmpty(setkey))
key = setkey;
var value = await _cache.GetStringAsync(key);
return new JsonResult(new { Code = 200, Message = "设置缓存成功", Data = "key=" + key + " value=" + value });
}

在 URL 添加 QueryString 可以设置缓存内容,如果没有带参数的话,就使用默认的值。

打开 https://localhost:5001/api/values/set 可以看到设置了默认值。

或者访问 https://localhost:5001/api/values/set?setkey=key11111&setvalue=asafesfdsreg

自定义设置缓存值。

打开 https://localhost:5001/api/values/get?setkey=key11111

可以获取缓存值。

设置缓存过期时间

使用 DistributedCacheEntryOptions 可以设置缓存过期时间

DistributedCacheEntryOptions 有三个属性,表示相对时间、绝对时间。

使用方法

        [HttpGet("Set")]
public async Task<JsonResult> SetCache(string setkey, string setvalue)
{ string key = "key1";
if (!string.IsNullOrEmpty(setkey))
key = setkey;
string value = DateTime.Now.ToLongTimeString();
if (!string.IsNullOrEmpty(setvalue))
value = setvalue; var options = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(20)); await _cache.SetStringAsync(key, value, options);
return new JsonResult(new { Code = 200, Message = "设置缓存成功", Data = "key=" + key + " value=" + value });
}

缓存 20 秒,20秒过后此缓存将被清除。

最新文章

  1. 22.mongodb副本集集群
  2. HDFS命令行操作
  3. C++ 文件操作(CFile类)
  4. java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0 *&amp;* 解决方法
  5. USACO6.4-The Primes
  6. Http 信息头
  7. c显示数字的LED(数字转LED)
  8. ASP.NET 异步编程
  9. 关于No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=armv7 armv7s)使用百度地图的解决办法
  10. Delphi ADO数据操作封装类
  11. Linux显示包含全部的文件系统
  12. IPFS:Filecoin和复制证明
  13. Electron的代码调试
  14. go的net/rpc用法
  15. shell脚本[] [[]] -n -z 的含义解析
  16. Debian-Linux配置网卡网络方法
  17. Python之数据加密与解密及相关操作(hashlib、hmac、random、base64、pycrypto)
  18. div展现与收起效果(鼠标移入移出)
  19. python3下载图片
  20. git查看各个branch之间的关系

热门文章

  1. C语言程序设计100例之(24):数制转换
  2. Python Weekly 419
  3. .NET Application,Session,Cookie,ViewState,Cache对象用法
  4. SpringBoot2.0 基础案例(17):自定义启动页,项目打包和指定运行环境
  5. 传统jdbc存在的问题总结
  6. sql server 2014 卸载
  7. 【Angular】学习笔记-环境部署、项目建立相关
  8. 【Java基础】Java中的反射机制
  9. Saltstack_使用指南12_配置管理-jinja模板
  10. MySQL数据篇(九)--存储过程实现定时每天清理过期数据