Azure Redis Cache结合Entra ID认证在.NET 8 API中的配置问题
我正尝试在.NET 8 API中集成Azure Redis Cache,已添加连接字符串并编写如下代码:
services.AddStackExchangeRedisCache( options => { options.Configuration = builder.Configuration.GetConnectionString("RedisCache"); options.InstanceName = builder.Environment.EnvironmentName; }) .AddDistributedMemoryCache();
当连接字符串中包含密码时该配置可正常工作,但我希望使用Entra ID认证替代密码。已启用Entra ID认证选项,为对应的Azure Web App分配了data owner权限,但移除密码后出现以下错误:
StackExchange.Redis.RedisConnectionException: 'The message timed out in the backlog attempting to send because no connection became available (5000ms) - Last Connection Exception: AuthenticationFailure on tsg-pas-dev-redis.redis.cache.windows.net:6380/Interactive, Flushed/ComputeResult, last: ECHO, origin: SetResult, outstanding: 0, last-read: 0s ago, last-write: 0s ago, keep-alive: 60s, state: ConnectedEstablishing, mgr: 9 of 10 available, last-heartbeat: never, global: 0s ago, v: 2.6.122.38350, command=SET, timeout: 5000, inst: 12, qu: 1, qs: 0, aw: False, bw: SpinningDown, rs: ReadAsync, ws: Flushed, in: 0, last-in: 0, cur-in: 0, sync-ops: 1, async-ops: 1, serverEndpoint: tsg-pas-dev-redis.redis.cache.windows.net:6380, conn-sec: 0.23, aoc: 0, mc: 1/1/0, mgr: 10 of 10 available, clientName: DBSX1Y6-54977(SE.Redis-v2.6.122.38350), IOCP: (Busy=1,Free=999,Min=8,Max=1000), WORKER: (Busy=1,Free=32766,Min=8,Max=32767), POOL: (Threads=15,QueuedItems=0,CompletedItems=347,Timers=3), v: 2.6.122.38350'
Exception: Error: NOAUTH Authentication required. Verify if the Redis password provided is correct. Attempted command: ECHO
请问我遗漏了什么配置?我记得其他服务需要在主程序中获取/初始化令牌,不确定是否与此相关。
编辑内容
根据下方回答我进行了修改,以便仍能使用IDistributedCache,本地可继续使用MemoryCache:
public static void AddDistributedCache(this IServiceCollection services, WebApplicationBuilder builder) { if (builder.Configuration["UseMemoryCache"]?.Equals("yes", StringComparison.OrdinalIgnoreCase) ?? true) { services.AddDistributedMemoryCache(); } else { services.AddStackExchangeRedisCache(options => { options.InstanceName = builder.Environment.EnvironmentName; options.ConnectionMultiplexerFactory = () => ConnectionMultiplexerFactory(builder); }) .AddDistributedMemoryCache(); } } private static async Task<IConnectionMultiplexer> ConnectionMultiplexerFactory(WebApplicationBuilder builder) { var configurationOptions = await ConfigurationOptions.Parse(builder.Configuration.GetConnectionString("RedisCache")!) .ConfigureForAzureWithTokenCredentialAsync("XXXX", new DefaultAzureCredential()); var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions); return connectionMultiplexer; }
其中XXXX需要从appsettings获取,我尚不理解为何需要该参数,且在同一Redis实例多应用场景下不够便捷,但至少无需密码。优点是可轻松切换缓存,无需关注multiplexer的getDatabase等操作。
内容的提问来源于stack exchange,提问作者Roelant M

