I'm adding a Redis token cache with data protection and also persisting the data protection keys to Redis (Propably a different Redis cache located somewhere other than the same token cache server). I'm just not sure if I should create and reuse the same 'ConnectionMultiplexer' here
services.AddStackExchangeRedisCache(redisCacheOptions =>
{
redisCacheOptions.ConnectionMultiplexerFactory = redis;
}
as I'm using here
services.AddDataProtection()
.SetApplicationName(appName)
.PersistKeysToStackExchangeRedis(redis, $"{appName}_DataProtection-Keys");
Or just have the AddStackExchangeRedisCache take care of it by itself?
If yes, how would I do that and still being able to dispose of it? And should I add a different name and endpoints each time it is used?
I'm new at this, so I would appreciate some help :)
I'm adding a Redis token cache with data protection and also persisting the data protection keys to Redis (Propably a different Redis cache located somewhere other than the same token cache server). I'm just not sure if I should create and reuse the same 'ConnectionMultiplexer' here
services.AddStackExchangeRedisCache(redisCacheOptions =>
{
redisCacheOptions.ConnectionMultiplexerFactory = redis;
}
as I'm using here
services.AddDataProtection()
.SetApplicationName(appName)
.PersistKeysToStackExchangeRedis(redis, $"{appName}_DataProtection-Keys");
Or just have the AddStackExchangeRedisCache take care of it by itself?
If yes, how would I do that and still being able to dispose of it? And should I add a different name and endpoints each time it is used?
I'm new at this, so I would appreciate some help :)
Share Improve this question edited Mar 17 at 6:42 Brando Zhang 28.7k6 gold badges42 silver badges70 bronze badges asked Mar 13 at 10:48 Super userSuper user 14 bronze badges1 Answer
Reset to default 0This is according to your actually requirement, normally, reuse the same ConnectionMultiplexer instance across different parts of your application is generally recommended to avoid the overhead of creating multiple connections.
The ConnectionMultiplexerFactory is design for reusing connections to caches.
Also the ConnectionMultiplexer is thread safe and for consideruing the dispose for it, I suggest you could consider register it as a singletion.
Like below:
IConnectionMultiplexer connectionMultiplexer =
ConnectionMultiplexer.Connect(connectionString);
builder.Services.AddSingleton(connectionMultiplexer);
builder.Services.AddStackExchangeRedisCache(options =>
{
options.ConnectionMultiplexerFactory =
() => Task.FromResult(connectionMultiplexer);
});