ASP.NET Core 3.1 MVC中如何将Redis用作OutputCacheProvider
Redis页面输出缓存实现方案(ASP.NET Core 3.1 MVC)
前置准备
首先安装所需NuGet包:
Microsoft.Extensions.Caching.StackExchangeRedis微软官方Redis分布式缓存实现System.Text.Json(如果项目未自带,用于序列化缓存内容)
步骤1:添加Redis配置
在appsettings.json中新增配置节点,参数直接对应你原有web.config中的配置:
"RedisOutputCache": { "ConnectionString": "rdstest.............:xxxx,password=xxxxxx=,ssl=true,abortConnect=false", "DatabaseId": 1, "InstanceName": "xxxx" }
参数对应说明:原web.config中的host+port、accessKey、ssl拼接到ConnectionString中,databaseId对应配置中的DatabaseId,applicationName对应InstanceName
步骤2:实现Redis响应缓存存储
ASP.NET Core 3.1默认的响应缓存仅支持内存存储,需自定义实现IResponseCache接口对接Redis:
using Microsoft.AspNetCore.ResponseCaching; using Microsoft.Extensions.Caching.Distributed; using System.Text.Json; public class RedisResponseCache : IResponseCache { private readonly IDistributedCache _redisCache; public RedisResponseCache(IDistributedCache redisCache) { _redisCache = redisCache; } public IResponseCacheEntry Get(string key) { var cacheData = _redisCache.Get(key); return cacheData == null ? null : JsonSerializer.Deserialize<ResponseCacheEntry>(cacheData); } public void Set(string key, IResponseCacheEntry entry, TimeSpan validFor) { var data = JsonSerializer.SerializeToUtf8Bytes(entry); _redisCache.Set(key, data, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = validFor }); } }
步骤3:注册服务与中间件
修改Startup.cs文件:
ConfigureServices方法中注册服务:
// 注册Redis分布式缓存 services.AddStackExchangeRedisCache(options => { var redisConfig = Configuration.GetSection("RedisOutputCache"); options.Configuration = redisConfig["ConnectionString"]; options.ConfigurationOptions.DefaultDatabase = int.Parse(redisConfig["DatabaseId"]); options.InstanceName = redisConfig["InstanceName"]; }); // 替换默认响应缓存存储为Redis实现 services.AddSingleton<IResponseCache, RedisResponseCache>(); // 注册响应缓存服务 services.AddResponseCaching(); // 原有MVC注册逻辑保留即可 services.AddControllersWithViews();
Configure方法中启用响应缓存中间件
注意中间件顺序必须放在UseRouting之后,UseAuthorization/UseEndpoints之前
app.UseRouting(); // 启用响应缓存 app.UseResponseCaching(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
步骤4:使用页面缓存
在需要缓存的Action上添加[ResponseCache]属性即可,配置规则和旧版OutputCache基本一致:
// 示例:缓存10分钟,随所有查询参数变化缓存 [ResponseCache(Duration = 600, VaryByQueryKeys = new[] { "*" })] public IActionResult Index() { // 业务逻辑 return View(); }
可根据需求调整参数:如需按用户标识缓存可添加VaryByHeader = "Cookie",如需固定缓存不同路径可省略VaryByQueryKeys等
内容的提问来源于stack exchange,提问作者user9020594
相关产品推荐
相关产品推荐

