How to use Redis Cache in .NET Core 3.1?

Redis is a high performance distributed cache for those need to store data and use again and again in a short period of time.

Step 1. Add the Redis caching package provided by Microsoft

Install-Package Microsoft.Extensions.Caching.StackExchangeRedis

Step 2. Open the startup.cs and add the following Configure Services

services.AddStackExchangeRedisCache(option =>
{
   option.Configuration = Configuration["127.0.0.1:6379,password=<redis-password>"];
});

Step 3. Get and Set Cache String Object

[Route("api/[controller]")]
public class HomeController : Controller
{
	private readonly IDistributedCache _distributedCache;

	public HomeController(IDistributedCache distributedCache)
	{
		_distributedCache = distributedCache;
	}

	[HttpGet]
	public IActionResult Get()
        {  
		var cacheKey = "cacheKey";
		var str = _distributedCache.GetString(cacheKey);
		if (!string.IsNullOrEmpty(str))
		{
			return "Get string from cache : " + str;
		}
		else
		{
			str = "Testing Cache";
			_distributedCache.SetString(cacheKey, str);
			return "Add string to cache : " + str;
		}
	}
}

That’s it.

Leave a Reply

Your email address will not be published.