How to use Redis Cache in ASP.NET Core
By FoxLearn 2/18/2024 9:12:33 AM 218
The Redis Cache is an open source, in-memory data structure store and used as a database to cache and message broker.
The first thing you need to install the Redis Cache to your project, you can use Manage Nuget Packages or Run the Nuget command line in visual studio as the following.
Install-Package Microsoft.Extensions.Caching.Redis
Open your Startup.cs class, then add a configuration that will allow your website to support Redis Cache.
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDistributedRedisCache(option => { option.Configuration = "127.0.0.1"; option.InstanceName = "master"; }); }
Remark: 127.0.0.1 is local IP, you can change the IP in the real world
Create a web API controller to practice the demo as shown below
[Route("api/[controller]")] public class HomeController : Controller { private readonly IDistributedCache _distributedCache; public HomeController(IDistributedCache distributedCache) { _distributedCache = distributedCache; } [HttpGet] public async Task<string> Get() { var cacheKey = "C-SharpCode"; var existing = _distributedCache.GetString(cacheKey); if (!string.IsNullOrEmpty(existing)) { return "Fetch data from cache instead from database"; } else { existing = DateTime.UtcNow.ToString(); //You will get data from your database, then set to redis cache _distributedCache.SetString(cacheKey, existing); return "Your data from database or redis cache"; } } }
The IDistributedCache interface has async methods, so you should use these methods in all possible scenarios.
This interface allows storing string values or byte. If you want to serialize an object and store the whole object, you can serialize it to bytes and save it as bytes, or serialize it to JSON format, and save it as a string if you prefer.