在ASP.NET核心控制器中使用StackExchange.Redis

Naa*_*kie 11 dependency-injection redis asp.net-core

我想使用Redis功能,例如来自MVC控制器的位域和哈希字段.据我所知,ASP.NET核心内置了缓存支持,但这只支持基本的GET和SET命令,而不支持我在应用程序中需要的命令.我知道如何从普通(例如.控制台)应用程序使用StackExchange.Redis,但我不知道如何在ASP站点中设置它.

我应该在哪里放置所有连接初始化代码,以便之后可以从控制器访问它?这是我会使用依赖注入的东西吗?

Tre*_*ler 21

在Startup类的ConfigureServices方法中,您需要添加

services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect("yourConnectionString"));
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过将构造函数签名更改为以下内容来使用依赖项注入:

public YourController : Controller
{
    private IConnectionMultiplexer _connectionMultiplexer;
    public YourController(IConnectionMultiplexer multiplexer)
    {
        this._connectionMultiplexer = multiplexer;
    }
}
Run Code Online (Sandbox Code Playgroud)


Naa*_*kie 7

这篇博客有一篇关于在ASP.NET Core中实现redis服务的文章(附带完整的代码回购).它有一个样板服务,可以自动将POCO类序列化为redis哈希集.


Ond*_*nek 5

简单的方法是安装Nuget包

Install-Package Microsoft.Extensions.Caching.Redis 
Run Code Online (Sandbox Code Playgroud)

在您的 ASP MVC .NET Core 项目中。

然后在您的类 Startup 中的 ConfigureServices 方法中使用依赖注入配置服务:

        services.AddDistributedRedisCache(option =>
        {
            option.Configuration = Configuration["AzureCache:ConnectionString"];
            option.InstanceName = "master";
        });
Run Code Online (Sandbox Code Playgroud)

在 appsettings.json 中添加绑定连接字符串以进行发布部署,如下所示:

"AzureCache": {
    "ConnectionString": "" 
  }  
Run Code Online (Sandbox Code Playgroud)

如果您使用 Azure,请在应用程序设置中为您的 ASP MVC .NET Core 应用服务添加应用设置名称,以便在部署后在 Azure 端运行时进行绑定。出于安全原因,用于生产的连接字符串不应出现在您的代码中。

Azure 绑定连接字符串

添加绑定,例如开发 appsettings.Development.json

"AzureCache": {
    "ConnectionString": "<your connection string>"
  }
Run Code Online (Sandbox Code Playgroud)

在构造函数中将服务注入控制器:

public class SomeController : Controller
{
        public SomeController(IDistributedCache distributedCache)
Run Code Online (Sandbox Code Playgroud)

  • 这看起来很漂亮,但请记住,这仅实现了一个“IDistributedCache”,它是 Redis 的一个非常有限的实现。更多信息:https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.caching.distributed.idistributedcache?view=aspnetcore-2.2 (2认同)