netcore redis 存储集合_ASP.NET Core教程:ASP.NET Core中使用Redis缓存

本文详细介绍了如何在ASP.NET Core项目中使用StackExchange.Redis库进行Redis缓存操作。从安装Redis和RedisDesktopManager,到在NuGet上安装StackExchange.Redis,再到配置appsettings.json,创建Redis帮助类,添加服务依赖项,最后在控制器中使用并测试Redis缓存功能。通过实例展示了如何存储和获取数据,以及如何通过RedisDesktopManager检查缓存内容。
摘要由CSDN通过智能技术生成

一、前言

我们这里以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帮助类,代码如下:

usingStackExchange.Redis;usingSystem;usingSystem.Collections.Concurrent;namespaceRedisDemo

{public classRedisHelper : IDisposable

{//连接字符串

private string_connectionString;//实例名称

private string_instanceName;//默认数据库

private int_defaultDB;private ConcurrentDictionary_connections;public RedisHelper(string connectionString, string instanceName, int defaultDB = 0)

{

_connectionString=connectionString;

_instanceName=instanceName;

_defaultDB=defaultDB;

_connections= new ConcurrentDictionary();

}///

///获取ConnectionMultiplexer///

///

privateConnectionMultiplexer GetConnect()

{return _connections.GetOrAdd(_instanceName, p =>ConnectionMultiplexer.Connect(_connectionString));

}///

///获取数据库///

///

/// 默认为0:优先代码的db配置,其次config中的配置

///

publicIDatabase GetDatabase()

{returnGetConnect().GetDatabase(_defaultDB);

}public IServer GetServer(string configName = null, int endPointsIndex = 0)

{var confOption =ConfigurationOptions.Parse(_connectionString);returnGetConnect().GetServer(confOption.EndPoints[endPointsIndex]);

}public ISubscriber GetSubscriber(string configName = null)

{returnGetConnect().GetSubscriber();

}public voidDispose()

{if (_connections != null && _connections.Count > 0)

{foreach (var item in_connections.Values)

{

item.Close();

}

}

}

}

}

五、添加服务依赖项

在Startup.cs类的ConfigureServices方法里面添加服务注入:

usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;namespaceRedisDemo

{public classStartup

{publicStartup(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 voidConfigureServices(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(newRedisHelper(_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 voidConfigure(IApplicationBuilder app, IHostingEnvironment env)

{if(env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

app.UseMvc();

}

}

}

六、在控制器中使用

新建一个控制器,然后通过构造函数注入:

usingMicrosoft.AspNetCore.Mvc;usingStackExchange.Redis;namespaceRedisDemo.Controllers

{

[Route("api/redis")]

[ApiController]public classRedisController : ControllerBase

{private readonlyIDatabase _redis;publicRedisController(RedisHelper client)

{

_redis=client.GetDatabase();

}

[HttpGet]public stringGet()

{//往Redis里面存入数据

_redis.StringSet("Name", "Tom");//从Redis里面取数据

string name = _redis.StringGet("Name");returnname;

}

}

}

七、测试

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值