ASP.NET?Core中使用Redis實(shí)現(xiàn)緩存
一、前言
我們這里以StackExchange.Redis為例,講解如何在ASP.NET Core中如何使用Redis實(shí)現(xiàn)緩存。首先需要安裝Redis和RedisDesktopManager。RedisDesktopManager用來查看Redis緩存里面的數(shù)據(jù)。如何安裝Redis這里不在講述。
二、安裝StackExchange.Redis
在NuGet上安裝StackExchange.Redis,如下圖所示:

安裝完成以后在依賴項(xiàng)里面就可以看到:

三、添加配置
在appsettings.json文件里面添加Redis相關(guān)配置信息:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"Redis": {
"Default": {
"Connection": "127.0.0.1:6379",
"InstanceName": "local",
"DefaultDB": 8
}
}
}四、Redis幫助類
創(chuàng)建Redis幫助類,代碼如下:
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
namespace RedisDemo
{
public class RedisHelper : IDisposable
{
//連接字符串
private string _connectionString;
//實(shí)例名稱
private string _instanceName;
//默認(rèn)數(shù)據(jù)庫
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>
/// 獲取數(shù)據(jù)庫
/// </summary>
/// <param name="configName"></param>
/// <param name="db">默認(rèn)為0:優(yōu)先代碼的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();
}
}
}
}
}五、添加服務(wù)依賴項(xiàng)
在Startup.cs類的ConfigureServices方法里面添加服務(wù)注入:
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;
//實(shí)例名稱
string _instanceName = section.GetSection("InstanceName").Value;
//默認(rèn)數(shù)據(jù)庫
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();
}
}
}六、在控制器中使用
新建一個控制器,然后通過構(gòu)造函數(shù)注入:
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里面存入數(shù)據(jù)
_redis.StringSet("Name", "Tom");
// 從Redis里面取數(shù)據(jù)
string name = _redis.StringGet("Name");
return name;
}
}
}七、測試
運(yùn)行程序,使用Postman測試控制器:

然后通過RedisDesktopManager查看Redis里面的數(shù)據(jù),這里使用的Db8數(shù)據(jù)庫:

到此這篇關(guān)于ASP.NET Core中使用Redis實(shí)現(xiàn)緩存的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
.NET Framework常用ORM框架iBatis.Net操作數(shù)據(jù)庫的方法
iBatis.Net 是一個輕量級的 ORM 框架,它允許開發(fā)者通過直接編寫 SQL 查詢來操作數(shù)據(jù)庫,并將查詢結(jié)果映射到對象模型中,本文將通過實(shí)際的代碼示例,詳細(xì)介紹如何在 .NET 環(huán)境中使用 iBatis.Net 進(jìn)行數(shù)據(jù)庫操作,感興趣的朋友一起看看吧2024-08-08
.net core使用redis基于StackExchange.Redis
這篇文章主要為大家詳細(xì)介紹了.net core使用redis基于StackExchange.Redis的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
利用Asp.Net Core的MiddleWare思想如何處理復(fù)雜業(yè)務(wù)流程詳解
這篇文章主要給大家介紹了關(guān)于利用Asp.Net Core的MiddleWare思想如何處理復(fù)雜業(yè)務(wù)流程的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起看看吧2018-08-08
asp.net 不用GridView自帶刪除功能,刪除一行數(shù)據(jù)
數(shù)據(jù)表一定要有個ID的主鍵值,你的gridview要設(shè)定一下DataKeyNames="ID"這個屬性值,接下的事件就好多了,寫個OnRowDeleting事件就可以了。2009-11-11
Asp.net 連接MySQL的實(shí)現(xiàn)代碼[]
ASP.NET連接MySQL需要一個組件(.net本身不提供訪問MySQL的驅(qū)動)MySQL.Data.Dll,此為官方提供(純C#開發(fā),開源噢),有多個版本選擇,采用的數(shù)據(jù)訪問模式為ADO.NET,跟asp.net訪問sqlserver很像,非常簡單。2009-08-08
Asp.net XMLHTTP封裝類(GET,Post發(fā)送和接收數(shù)據(jù))
XMLHTTP封裝類可以向遠(yuǎn)程發(fā)送URL和參數(shù),接受返回信息(無亂碼)2008-11-11
ASP.NET MVC5網(wǎng)站開發(fā)修改及刪除文章(十)
這篇文章主要為大家詳細(xì)介紹了ASP.NET MVC5網(wǎng)站開發(fā)修改及刪除文章,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2015-09-09

