【发布时间】:2021-12-09 14:56:28
【问题描述】:
我正在尝试连接到 Azure Redis 缓存。我正在使用 .net 6 并使用 StackExchangeRedis 缓存响应,它在 localhost 中有效,但在部署中不起作用,请帮助我.... 我也在许多论坛中找到了答案,但不起作用
我的 Redis 代码配置
应用程序.json
"RedisCacheSetting": {
"Enabled": true,
"ConnectionString": "tutor-helper.redis.cache.windows.net:6380,password=*****PuCERKKnrcbff0y3hWpZ***m1BaY40=,ssl=True,abortConnect=False"
},
缓存属性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CachedAttribute : Attribute, IAsyncActionFilter
{
private readonly int _timeToLiveSeconds;
public CachedAttribute(int timeToLiveSeconds)
{
_timeToLiveSeconds = timeToLiveSeconds;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var cacheSetting = context.HttpContext.RequestServices.GetRequiredService<RedisCacheSetting>();
if (!cacheSetting.Enabled)
{
await next();
return;
}
var cacheService = context.HttpContext.RequestServices.GetRequiredService<IResponseCacheService>();
var cacheKey = GenerateKeyFromRequest(context.HttpContext.Request);
var cacheResponse = await cacheService.GetCacheResponseAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheResponse))
{
var rs = new ContentResult
{
Content = cacheResponse,
ContentType = "application/json",
StatusCode = 200,
};
context.Result = rs;
return;
}
var executedContext = await next();
if (executedContext.Result is ObjectResult okObjectResult)
{
await cacheService.CacheResponseAsync(cacheKey, okObjectResult.Value, TimeSpan.FromSeconds(_timeToLiveSeconds));
}
}
private static string GenerateKeyFromRequest(HttpRequest request)
{
var keyBuilder = new StringBuilder();
keyBuilder.Append($"{request.Path}");
foreach (var (key, value) in request.Query.OrderBy(x => x.Key))
{
keyBuilder.Append($"|{key}-{value}");
}
return keyBuilder.ToString();
}
}
startup.cs 中的配置
public static void SetUpCache(this IServiceCollection services, IConfiguration configuration)
{
var redisCache = new RedisCacheSetting();
configuration.GetSection(nameof(RedisCacheSetting)).Bind(redisCache);
services.AddSingleton(redisCache);
//services.Configure<RedisCacheSetting>(configuration.GetSection("RedisCacheSetting"));
//services.AddDistributedRedisCache(op => op.Configuration = redisCache.ConnectionString);
services.AddStackExchangeRedisCache(op => op.Configuration = redisCache.ConnectionString);
services.AddSingleton<IResponseCacheService, ResponseCacheService>();
}
【问题讨论】:
标签: asp.net stackexchange.redis azure-redis-cache