How to implement a distributed cache in ASP.NET Core
By FoxLearn 1/7/2025 9:25:52 AM 43
What is a distributed cache?
Distributed caches enhance application performance and scalability by allowing multiple application servers to share cached data, which is stored centrally instead of on individual web servers. Additionally, the cache persists through server restarts, and adding or removing servers doesn't affect the cached data.
In ASP.NET Core, the IDistributedCache interface is used for working with distributed caches, which differs from the IMemoryCache interface, as we will explore next.
IDistributedCache interface
The IDistributedCache interface used for distributed caching in .NET Core is more intricate than the IMemoryCache interface, which caches data in the memory of a single web server.
public interface IMemoryCache : IDisposable { bool TryGetValue(object key, out object value); ICacheEntry CreateEntry(object key); void Remove(object key); }
In contrast, the IDistributedCache interface is designed for scenarios involving a web farm. It includes a range of synchronous and asynchronous methods that allow you to add, retrieve, or remove items from a centralized cache.
public interface IDistributedCache { byte[] Get(string key); Task<byte[]> GetAsync(string key); void Set(string key, byte[] value, DistributedCacheEntryOptions options); Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options); void Refresh(string key); Task RefreshAsync(string key); void Remove(string key); Task RemoveAsync(string key); }
While IDistributedCache works with byte[] data, the framework provides extension methods to work with string objects as well. You can also create your own extension methods to handle custom data types if necessary.
Implementing Distributed Cache in .NET Core with Redis
To use Redis as a distributed cache in .NET Core, start by installing the Redis package with the following command in the NuGet Package Manager console:
Install-Package Microsoft.Extensions.Caching.Redis
Next, enable Redis as a distributed cache by configuring it in the ConfigureServices
method in Startup.cs
:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDistributedRedisCache(option => { option.Configuration = "localhost"; option.InstanceName = "FOXLEARN"; }); }
To use the IDistributedCache
interface in your controller, you can insert or retrieve data from Redis as follows:
public class DefaultController : Controller { private readonly IDistributedCache _distributedCache; public HomeController(IDistributedCache distributedCache) { _distributedCache = distributedCache; } [HttpGet] public async Task<string> Get() { var cacheKey = "FOXLEARN"; var data = _distributedCache.GetString(cacheKey); if (!string.IsNullOrEmpty(data)) { return data; // Retrieved from Cache } else { string str = "Hello World"; _distributedCache.SetString(cacheKey, str); return str; } } }
For using SQL Server as a distributed cache, install the following NuGet package:
Install-Package Microsoft.Extensions.Caching.SqlServer
Then, configure it in the ConfigureServices
method:
services.AddDistributedSqlServerCache(x => { x.ConnectionString = Configuration["ConnectionStrings:Default"]; x.SchemaName = "dbo"; x.TableName = "AspNetCache"; });
To create the necessary database tables for SQL Server caching, install the Microsoft.Extensions.Caching.SqlConfig.Tools
package and run the following command:
dotnet sql-cache create <connection string> <schema> <table name>
ASP.NET Core abstracts distributed caching, providing a consistent API via the IDistributedCache
interface, whether using Redis or SQL Server.