Using Azure Redis Cache On Your .NET Core Application - Part one

this article, we will see how to use Azure Redis cache to cache your data and provide a faster way of loading the web pages to the users.

What is the Azure Redis cache?

Azure Redis Cache is based on the popular open source Redis cache. It gives you access to a secure, dedicated Redis cache, managed by Microsoft and accessible from any application within Azure.

Why would I use the Azure Redis Cache?

Azure Redis Cache helps your application become more responsive even as the customer load increases. It takes advantage of the low-latency, high-throughput capabilities of the Redis engine. This separate, distributed cache layer allows your data tier to scale independently for more efficient use of the compute resources in your application layer.

How do I use it?

Let's go to the best part.. follow these steps to reproduce:

  • First, you must have your Azure Redis Cache set up.

    Azure

  • Wait until it finishes deploying (it takes some minutes, do not worry).

    Azure

  • Now, create a new MVC ASP.NET Core project and install the NuGet package: Microsoft.Extensions.Caching.Redis.Core

  • With your environment and the Redis cache ready, let's start configuring your project with the settings from the Redis cache in order to make them communicate. First, get the Redis cache connection string from the Redis Cache panel.

    Azure
  • Update your appsettings.json to add the connection string from your Redis Cache.
    1. "ConnectionStrings": {  
    2. "RedisConnection""TVtesting.redis.cache.windows.net:6380,password=XXXXXXXXXXXXXXXX,ssl=True,abortConnect=False" }  
  • Update your Startup class in the ConfigureServices method.
    1. public void ConfigureServices(IServiceCollection services) {  
    2.     // Add framework services.  
    3.     services.AddMvc();  
    4.     services.AddDistributedRedisCache(options => {  
    5.         options.Configuration = Configuration.GetConnectionString("RedisConnection");  
    6.         options.InstanceName = "TVTesting"// Your DNS Name  
    7.     });  
    8. }  
Update your Controller constructor to receive the cache object passed by dependency injection and use your cache object to set and get the cached data.
  1. public class HomeController: Controller {  
  2.     private IDistributedCache _cache;  
  3.     public HomeController(IDistributedCache cache) {  
  4.         this._cache = cache;  
  5.     }  
  6.     public IActionResult Index() {  
  7.         string test = _cache.GetString("Test") ? ? "";  
  8.         if (string.IsNullOrEmpty(test)) {  
  9.             _cache.SetString("Test""Tested");  
  10.             test = _cache.GetString("Test") ? ? "";  
  11.         }  
  12.         ViewData["Test"] = test;  
  13.         return View();  
  14.     }  
  15. }  
Congratulations! You have successfully set up your Azure Redis Cache.