How do you configure Redis as the backing distributed cache for both IDistributedCache and Output Caching in the same application?
Short answer
AddStackExchangeRedisCache() registers IDistributedCache backed by Redis, while a separate output caching store configuration (via a Redis-backed IOutputCacheStore implementation) lets Output Caching also persist to the same Redis instance rather than the default in-memory…
Advertisement
AModel answer
AddStackExchangeRedisCache() registers IDistributedCache backed by Redis, while a separate output caching store configuration (via a Redis-backed IOutputCacheStore implementation) lets Output Caching also persist to the same Redis instance rather than the default in-memory store, ensuring both application-level data caching and HTTP output caching benefit from the same shared, distributed backing store across multiple server instances.
builder.Services.AddStackExchangeRedisCache(options => {
options.Configuration = builder.Configuration.GetConnectionString("Redis");
});
builder.Services.AddOutputCache(options => {
options.AddBasePolicy(policy => policy.Expire(TimeSpan.FromMinutes(5)));
});
// Redis-backed output cache store configured via a corresponding provider packageReal-world example
A horizontally-scaled API ensures both its manually-cached data (IDistributedCache) and its automatic output-cached responses share the same Redis instance, so cache coherency holds consistently across every caching mechanism the app uses.
Likely follow-ups
- What are the trade-offs of a shared Redis instance for both purposes versus separate instances?
- How does connection pooling work for StackExchange.Redis under high concurrency?
Related topics