ASP.NET Core 中的 Redis 缓存

     2023-02-19     158

关键词:

【中文标题】ASP.NET Core 中的 Redis 缓存【英文标题】:Redis Cache in ASP.NET Core 【发布时间】:2017-03-15 01:04:11 【问题描述】:

我是 Redis 新手,使用 VS 2015 和 ASP.NET Core 应用程序 (v 1.0),我安装了 nugget 包:

Install-Package StackExchange.Redis

但是我无法将其注入和配置到我的服务中,没有 RedisCache 或“AddDistributedRedisCache”方法。

如何注入和使用?

【问题讨论】:

您是否真的想使用Microsoft.Extensions.Caching.Redis,这是对分布式缓存的开箱即用的redis支持?它是 IDistrubutedCache 接口 github.com/aspnet/Caching/tree/1.0.0/src 的 3 个默认实现之一 我一开始就安装了 Microsoft.Extensions.Caching.Redis,但它与 .NET Core 不兼容,我猜它需要 Framework 4.5+。 StackExchange.Redis 仅包含一个 redis 客户端,它不会将自身实现到 ASP.NET Core 中。但是Microsofts distributed caching implementation uses Microsoft.Extensions.Caching.Redis, its just a wrapper around it and the IDistrubtedCache`接口。 github.com/aspnet/Caching/blob/dev/src/Microsoft.Extensions.Caching.Redis/RedisCache.cs 是的,没错。之前没注意。下一个版本将支持它。目前有一个包,但适用于 ASP.NET Core 1.1-preview1。我认为这是因为当 Microsoft 使用 ASP.NET Core 进行 RTM 时,Stackexchange.Redis 没有 .NET Core 的 RTM 版本 我猜,如果您从github.com/aspnet/Caching/tree/1.0.0/src/… 获取源并使用.NET Core 兼容版本的 StackExchange.Redis 包将其重新定位到 .NET Core,您应该可以使用它。 Caching.Redis 包不包含太多代码,只是大致包装了 SE.Redis 客户端。然后您可以立即使用它,而不是升级到尚未准备好生产的 ASP.NET Core 1.1-preview 【参考方案1】:
Install-Package StackExchange.Redis

Redis 服务:

public class RedisService : IDisposable

    private readonly IConnectionMultiplexer Connection;
    private readonly string _connectionString;


    public RedisService(IConfiguration Configuration, ILogger<RedisService> logger)
    
        _connectionString = Configuration.GetConnectionString("redis connection string");

        var conn = new Lazy<IConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_connectionString));
        Connection = conn.Value;

        Main = Connection.GetDatabase(1); 


        logger.LogWarning("Redis Service Attached!");

    

    public IDatabase Main  get; 

   
    
    public void Dispose()
    
        Connection?.Dispose();
    

在startup.cs中添加服务

services.AddSingleton<RedisService>();

现在在你的控制器中使用它

【讨论】:

【参考方案2】:

我使用了以下解决方案并得到了答案。

1.下载 Redis-x64-3.0.504.msi 并安装(link)

2.从 Nuget 包管理器安装 Microsoft.Extensions.Caching.StackExchangeRedis

3.在Startup.cs类里面,在ConfigureServices方法中,添加这个命令:

 services.AddStackExchangeRedisCache(options => options.Configuration = "localhost:6379");

    将 IDistributedCache 注入控制器:

     private readonly IDistributedCache _distributedCache;
    
     public WeatherForecastController( IDistributedCache distributedCache)
     
         _distributedCache = distributedCache;
     
    

5.最后:

   [HttpGet]
    public async Task<List<string>> GetStringItems()
    
        string cacheKey = "redisCacheKey";
        string serializedStringItems;
        List<string> stringItemsList;

        var encodedStringItems = await _distributedCache.GetAsync(cacheKey);
        if (encodedStringItems != null)
        
            serializedStringItems = Encoding.UTF8.GetString(encodedStringItems);
            stringItemsList = JsonConvert.DeserializeObject<List<string>>(serializedStringItems);
        
        else
        
            stringItemsList = new List<string>()  "John wick", "La La Land", "It" ;
            serializedStringItems = JsonConvert.SerializeObject(stringItemsList);
            encodedStringItems = Encoding.UTF8.GetBytes(serializedStringItems);
            var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(1))
                .SetAbsoluteExpiration(TimeSpan.FromHours(6));
            await _distributedCache.SetAsync(cacheKey, encodedStringItems, options);

        
        return stringItemsList;
    

祝你好运!!!

【讨论】:

为什么我们要对序列化的 json 进行编码?我们可以将其保留为序列化的 json 本身吗?【参考方案3】:

01.从download下载最新的redis,从services.msc安装并启动redis服务

02.在project.json

中添加两个库
"Microsoft.Extensions.Caching.Redis.Core": "1.0.3",
"Microsoft.AspNetCore.Session": "1.1.0",

03.添加你的依赖注入

public void ConfigureServices(IServiceCollection services)
    
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();
        //For Redis
        services.AddSession();
        services.AddDistributedRedisCache(options =>
        
            options.InstanceName = "Sample";
            options.Configuration = "localhost";
        );
   

    并在 Configure 方法中添加 app.UseMvc 行的顶部

    app.UseSession();

在asp.net core的会话存储中使用redis。现在你可以在HomeController.cs

中这样使用
public class HomeController : Controller

    private readonly IDistributedCache _distributedCache;
    public HomeController(IDistributedCache distributedCache)
    
        _distributedCache = distributedCache;
    
    //Use version Redis 3.22
    //http://***.com/questions/35614066/redissessionstateprovider-err-unknown-command-eval
    public IActionResult Index()
    
        _distributedCache.SetString("helloFromRedis", "world");
        var valueFromRedis = _distributedCache.GetString("helloFromRedis");
        return View();
    
 

【讨论】:

它缺乏 StackExchange.Redis.Extension 旧非 .net 核心版本中存在的丰富功能。

Asp.Net Core:在控制器外使用内存缓存

】Asp.NetCore:在控制器外使用内存缓存【英文标题】:Asp.NetCore:Usememorycacheoutsidecontroller【发布时间】:2017-06-2207:40:45【问题描述】:在ASP.NETCore中,从控制器访问内存缓存非常容易在您的启动中添加:publicvoidConfigureServices(IServiceC... 查看详情

Asp.net Core 中的内存使用限制

】Asp.netCore中的内存使用限制【英文标题】:LimitationofmemoryusageinAsp.netCore【发布时间】:2016-12-1915:18:48【问题描述】:我在我的项目中使用IMemoryCache。我想知道如果我的应用程序将许多长期存在的对象推送到缓存中会发生什么。... 查看详情

在 ASP.NET Core 中缓存导航栏链接

】在ASP.NETCore中缓存导航栏链接【英文标题】:CachingnavbarlinksinASP.NETCore【发布时间】:2021-12-0906:02:15【问题描述】:我有一个ASP.NETCore应用程序,它根据用户的角色显示不同的导航栏链接。它首先检查用户是否登录。如果是,则... 查看详情

静态 ID - ASP.NET Core 分布式缓存标记帮助程序

】静态ID-ASP.NETCore分布式缓存标记帮助程序【英文标题】:StaticId-ASP.NETCoreDistributedCacheTagHelper【发布时间】:2021-07-1918:42:41【问题描述】:我们将ASP.NETCore分布式缓存标记助手与SQL服务器一起使用。<distributed-cachename="MyCacheItem1"e... 查看详情

ASP.Net Core 2.0 - ResponseCaching 中间件 - 不在服务器上缓存

】ASP.NetCore2.0-ResponseCaching中间件-不在服务器上缓存【英文标题】:ASP.NetCore2.0-ResponseCachingMiddleware-NotCachingonServer【发布时间】:2018-06-2207:24:14【问题描述】:我想在asp.netcore2.0中使用服务器端响应缓存(输出缓存),发现了Respons... 查看详情

C# Asp.Net Core 使用 Redis 进行 ADDDistributedMemoryCache 和数据保护

】C#Asp.NetCore使用Redis进行ADDDistributedMemoryCache和数据保护【英文标题】:C#Asp.NetCoreUseRedisforIDistributedMemoryCacheandDataProtection【发布时间】:2021-12-2105:35:33【问题描述】:正如标题所暗示的,我应该同时使用Redis作为DistributedCache并存... 查看详情

我是不是需要在 ASP.NET Core 中调用 AddMemoryCache 才能使缓存工作?

】我是不是需要在ASP.NETCore中调用AddMemoryCache才能使缓存工作?【英文标题】:DoINeedtoCallAddMemoryCacheinASP.NETCoreforCachetowork?我是否需要在ASP.NETCore中调用AddMemoryCache才能使缓存工作?【发布时间】:2017-06-1206:24:19【问题描述】:在最... 查看详情

如何在 ASP.NET core rc2 中禁用浏览器缓存?

】如何在ASP.NETcorerc2中禁用浏览器缓存?【英文标题】:HowtodisablebrowsercacheinASP.NETcorerc2?【发布时间】:2016-07-0618:56:12【问题描述】:我尝试了这个中间件,但浏览器仍在保存文件。我希望用户始终获得最新版本的js和css文件。pub... 查看详情

Asp.net Core 中的 UserHostAddress

】Asp.netCore中的UserHostAddress【英文标题】:UserHostAddressinAsp.netCore【发布时间】:2014-11-2517:22:24【问题描述】:旧的HttpContext.Request.UserHostAddress在Asp.NetCore中的等价物是什么?我尝试了this.ActionContext.HttpContext,但找不到UserHostAddress... 查看详情

asp.net core 3中的CorsAuthorizationFilterFactory

】asp.netcore3中的CorsAuthorizationFilterFactory【英文标题】:CorsAuthorizationFilterFactoryinasp.netcore3【发布时间】:2020-04-0700:06:31【问题描述】:我正在尝试将项目从asp.netCore2.2.6迁移到asp.netCore3.0在我的创业中,我有services.AddMvc(options=>opt... 查看详情

ASP.NET Core 中的异步延续在哪里排队?

】ASP.NETCore中的异步延续在哪里排队?【英文标题】:WhereisasynchronouscontinuationsarequeuedinASP.NETCore?【发布时间】:2019-05-2202:49:51【问题描述】:在旧版ASP.NET上,异步方法的延续排队到请求上下文(AspNetSynchronizationContext)。但是在ASP.N... 查看详情

ASP.NET Core 中的 PostAsJsonAsync 方法在哪里?

】ASP.NETCore中的PostAsJsonAsync方法在哪里?【英文标题】:WhereisthePostAsJsonAsyncmethodinASP.NETCore?【发布时间】:2016-10-1317:23:34【问题描述】:我在ASP.NETCore中寻找PostAsJsonAsync()扩展方法。Basedonthisarticle,它在Microsoft.AspNet.WebApi.Client程序... 查看详情

asp.net core中的Razor很慢

】asp.netcore中的Razor很慢【英文标题】:Razorinasp.netcoreisveryslow【发布时间】:2016-10-1001:33:33【问题描述】:我创建了一个小的asp.netcoremvc项目来测试asp.net应用程序在Linux(Ubuntu16.04)上的速度。我创建了与AspUser类(存储在PostgreSQL数... 查看详情

ASP.NET 中的缓存模式

】ASP.NET中的缓存模式【英文标题】:CachingPatternsinASP.NET【发布时间】:2010-09-0704:51:40【问题描述】:所以我刚刚修复了我正在开发的框架中的一个错误。伪伪代码如下所示:myoldObject=newMyObjectsomeValue="oldvalue";cache.Insert("myObjectKey",... 查看详情

ASP.net Core API 中的路由

】ASP.netCoreAPI中的路由【英文标题】:RoutesinASP.netCoreAPI【发布时间】:2017-04-1314:38:08【问题描述】:我在Asp.net核心中阅读了很多关于API路由的主题,但我无法使其工作。首先,这是我的控制器:PublicclassBXLogsController:Controller//[Htt... 查看详情

如何通过 ASP.NET Core 中的链接发布

】如何通过ASP.NETCore中的链接发布【英文标题】:HowtoPOSTviaalinkinASP.NETCore【发布时间】:2018-02-1917:01:42【问题描述】:我尝试通过链接发布到SetLanguage操作,但不确定如何完成以下代码:<formid="selectLanguage"asp-controller="Home"asp-acti... 查看详情

从 ASP.NET Core Blazor 中的 .NET 方法调用 JavaScript 函数

】从ASP.NETCoreBlazor中的.NET方法调用JavaScript函数【英文标题】:CallJavaScriptfunctionsfrom.NETmethodsinASP.NETCoreBlazor【发布时间】:2021-10-0123:29:00【问题描述】:我想从我的ASP.NETCoreBlazor应用程序调用的JavaScript函数:exportfunctiononClick(map)var... 查看详情

ASP.NET CORE 中的 Request.Files

】ASP.NETCORE中的Request.Files【英文标题】:Request.FilesinASP.NETCORE【发布时间】:2016-08-0807:02:21【问题描述】:我正在尝试使用ajax请求使用aspnet核心上传文件。在以前的.net版本中,我曾经使用来处理这个问题foreach(stringfileNameinRequest.... 查看详情