ASP.NET Core教程:ASP.NET Core中使用Redis缓存
参考网址:https://www.cnblogs.com/dotnet261010/p/12033624.html
一、前言
我们这里以StackExchange.Redis为例,讲解如何在ASP.NET Core中如何使用Redis实现缓存。首先需要安装Redis和RedisDesktopManager。RedisDesktopManager用来查看Redis缓存里面的数据。如何安装Redis这里不在讲述。
二、安装StackExchange.Redis
在NuGet上安装StackExchange.Redis,如下图所示:

安装完成以后在依赖项里面就可以看到:

三、添加配置
在appsettings.json文件里面添加Redis相关配置信息:

{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"Redis": {
"Default": {
"Connection": "127.0.0.1:6379",
"InstanceName": "local",
"DefaultDB": 8
}
}
}

四、Redis帮助类
创建Redis帮助类,代码如下:

using StackExchange.Redis;
using System;
using System.Collections.Concurrent; namespace RedisDemo
{
public class RedisHelper : IDisposable
{
//连接字符串
private string _connectionString;
//实例名称
private string _instanceName;
//默认数据库
private int _defaultDB;
private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
public RedisHelper(string connectionString, string instanceName, int defaultDB = 0)
{
_connectionString = connectionString;
_instanceName = instanceName;
_defaultDB = defaultDB;
_connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
} /// <summary>
/// 获取ConnectionMultiplexer
/// </summary>
/// <returns></returns>
private ConnectionMultiplexer GetConnect()
{
return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
} /// <summary>
/// 获取数据库
/// </summary>
/// <param name="configName"></param>
/// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
/// <returns></returns>
public IDatabase GetDatabase()
{
return GetConnect().GetDatabase(_defaultDB);
} public IServer GetServer(string configName = null, int endPointsIndex = 0)
{
var confOption = ConfigurationOptions.Parse(_connectionString);
return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
} public ISubscriber GetSubscriber(string configName = null)
{
return GetConnect().GetSubscriber();
} public void Dispose()
{
if (_connections != null && _connections.Count > 0)
{
foreach (var item in _connections.Values)
{
item.Close();
}
}
}
}
}

五、添加服务依赖项
在Startup.cs类的ConfigureServices方法里面添加服务注入:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; namespace RedisDemo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//redis缓存
var section = Configuration.GetSection("Redis:Default");
//连接字符串
string _connectionString = section.GetSection("Connection").Value;
//实例名称
string _instanceName = section.GetSection("InstanceName").Value;
//默认数据库
int _defaultDB = int.Parse(section.GetSection("DefaultDB").Value ?? "0");
services.AddSingleton(new RedisHelper(_connectionString, _instanceName, _defaultDB));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseMvc();
}
}
}

六、在控制器中使用
新建一个控制器,然后通过构造函数注入:

using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis; namespace RedisDemo.Controllers
{
[Route("api/redis")]
[ApiController]
public class RedisController : ControllerBase
{
private readonly IDatabase _redis;
public RedisController(RedisHelper client)
{
_redis = client.GetDatabase();
} [HttpGet]
public string Get()
{
// 往Redis里面存入数据
_redis.StringSet("Name", "Tom");
// 从Redis里面取数据
string name = _redis.StringGet("Name");
return name;
}
}
}

七、测试
运行程序,使用Postman测试控制器:

然后通过RedisDesktopManager查看Redis里面的数据,这里使用的Db8数据库:

ASP.NET Core教程:ASP.NET Core中使用Redis缓存的更多相关文章
- linux中的redis缓存服务器
Linux中的Redis缓存服务器 一.Redis基础部分: 1.redis介绍与安装比mysql快10倍以上 *****************redis适用场合**************** 1 ...
- 在springboot中使用redis缓存,将缓存序列化为json格式的数据
背景 在springboot中使用redis缓存结合spring缓存注解,当缓存成功后使用gui界面查看redis中的数据 原因 springboot缓存默认的序列化是jdk提供的 Serializa ...
- nopCommerce 3.9 大波浪系列 之 使用部署在Docker中的Redis缓存主从服务
一.概述 nop支持Redis作为缓存,Redis出众的性能在企业中得到了广泛的应用.Redis支持主从复制,HA,集群. 一般来说,只有一台Redis是不可行的,原因如下: 单台Redis服务器会发 ...
- redis的介绍与操作及Django中使用redis缓存
redis VS mysql的区别 """ redis: 内存数据库(读写快).非关系型(操作数据方便) mysql: 硬盘数据库(数据持久化).关系型(操作数据间关系) ...
- Java项目中使用Redis缓存案例
缓存的目的是为了提高系统的性能,缓存中的数据主要有两种: 1.热点数据.我们将经常访问到的数据放在缓存中,降低数据库I/O,同时因为缓存的数据的高速查询,加快整个系统的响应速度,也在一定程度上提高并发 ...
- 微信小程序大型系统架构中应用Redis缓存要点
在大型分布式系统架构中,必须选择适合的缓存技术以应对高并发,实现系统相应的高性能,酷客多小程序经过慎重选型,选择了采用基于腾讯云服务的Redis弹性缓存技术,结合Redis官方推荐的.NET驱动类库S ...
- 在NodeJS中使用Redis缓存数据
Redis数据库采用极简的设计思想,最新版的源码包还不到2Mb.其在使用上也有别于一般的数据库. node_redis redis驱动程序多使用 node_redis 此模块可搭载官方的 hiredi ...
- 在Window系统中使用Redis缓存策略
Redis是一个用的比较广泛的Key/Value的内存数据库,新浪微博.Github.StackOverflow 等大型应用中都用其作为缓存,Redis的官网为http://redis.io/. 最近 ...
- .NET Core教程--给API加一个服务端缓存啦
以前给API接口写缓存基本都是这样写代码: // redis key var bookRedisKey = ConstRedisKey.RecommendationBooks.CopyOne(book ...
随机推荐
- Pycharm上python运行和unittest运行两种执行方式解析
前言 经常有人在群里反馈,明明代码一样的啊,为什么别人的能出报告,我的出不了报告,为什么别人运行结果跟我的不一样啊... 这种问题先检查代码,确定是一样的,那就是运行姿势不对了,一旦导入unittes ...
- 「SDOI2016」数字配对
「SDOI2016」数字配对 题目大意 传送门 题解 \(a_i\) 是 \(a_j\) 的倍数,且 \(\frac{a_i}{a_j}\) 是一个质数,则将 \(a_i,a_j\) 质因数分解后,其 ...
- 深入学习Netty(4)——Netty编程入门
前言 从学习过BIO.NIO.AIO编程之后,就能很清楚Netty编程的优势,为什么选择Netty,而不是传统的NIO编程.本片博文是Netty的一个入门级别的教程,同时结合时序图与源码分析,以便对N ...
- 团队开发day04
通过myurl.openConnection()连接一直连接失败,问题解决: 在一般的Java Web程序开发中,我们通常使用localhost或者127.0.0.1来访问本机的Web服务, 但是如果 ...
- java集合(4)-Set集合
Set集合,类似于一个罐子,程序可以把多个对象"丢进"Set集合,而Set集合通常不能记住每个元素的添加顺序.Set集合与Collection基本相同,没有提供任何额外的方法.实际 ...
- 【剑指offer】51.构建乘积数组
51.构建乘积数组 知识点:数组: 题目描述 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0] * A[1] *... * A[i ...
- Leetcode6. Z 字形变换
> 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,按下右上下右上排列后输出字符串}) 3.查询结果 二.查询价格大于等于10的商品 js文 ...
- Blazor 事件处理开发指南
翻译自 Waqas Anwar 2021年3月25日的文章 <A Developer's Guide To Blazor Event Handling> [1] 如果您正在开发交互式 We ...