How to use Microsoft Azure Redis Cache?

Microsoft Azure Redis Cache offers us to use the popular open source Redis Cache ecosystem and reliable hosting of this service that is managed by Microsoft. In this post, I’ll tell you how to use Microsoft Azure Redis Cache with ASP.NET Core application. The same concepts can also be used for ASP.NET MVC applications.

The code for this application is available in my github repository. Get this repository and play with the application to try this amazing service from Microsoft to learn about it in detail.

Azure Redis Cache

Azure Redis Cache can be created using Azure portal > New > Redis Cache. To create this service, there will be few required information that Azure portal needs when you click on Create button. Information like DNS name, Subscription, Resource Group, Location and Pricing Tier. For this post, I’ve created a Redis Cache application named playarea that is part of a resource group named redis-play-area-rg. You may name these as per your choice. Based on the DNS name in the setup, the host name for my Redis service is playarea.redis.cache.windows.net.

Access Keys

To access this service in ASP.NET Core application, connection string will be required that is made up of host name, port, password and few other attributes. This connection string can be accessed using Access Keys area of the Redis service in Azure portal. There are two types of connection string available – Primary, Secondary. There is also an option to reset the values as and when required. This connection string looks like following:

ASP.NET Core application

I’ve used the starter template of type ASP.NET Core application to create a client web application that will consume the Azure Redis Cache service. Next, to actually use Redis service, a Nuget package named Microsoft.Extensions.Caching.Redis.Core is required in the project. I’m using version 1.0.3.

Next, in the appsettings.json file, I’ve pasted the connection string from Azure Portal with following entry in the json file as shown below. This connection string is then used in the application and can be changed when required without recompiling project code.

Configure Redis Cache as Service

ASP.NET Core application easily allow to configure services and add it to the default container using ConfigureServices method in Startup.cs file. This service will then be available to any consumer on demand just like using any third-party IoC framework in ASP.NET MVC application. After installing the package for Redis above, we can now register it using code below. It basically uses the connection string and also define instance name for Redis.

Next, our Azure Redis Cache service is ready to be used provided the connection string is valid and Azure Redis Cache is up and running.

Read and Write Operations

For caching, we just need a key and a value, where both the values are of type string. Any complex object can be serialised into string for write operation and can be deserialised to an object for read operation.

For this, I’m using another popular package named as Newtonsoft.Json. Just to demonstrate, I’ve create a class named Audit which looks like following:

Audit class definition

C#

1

2

3

4

5

6

publicclassAudit

{

publicstringName{get;set;}

publicDateTimeLastUpdated{get;set;}

}

This complex type is used for read and write operations for caching. For your project, it may be any data that you would like to cache.

Let’s now look at the HomeController.cs code. To keep this post simple, I’m using the cache directly in the controller but this can be abstracted behind a repository class if needed.

As such distributed Redis Cache service is now available to the container, it will be available on demand whenever a type is requested that implements IDistributedCache interface (line no. 7). This instance is then saved in a private member on line no. 3 so that it can be accessed from controller methods.

On line no. 12, cache member is used to get cache value based on a key named audit and then deserialised. If a cached value is available, it is then used in the View using ViewData (simplified for post, use a view-model in real application).

If a cached value is not available, then I’m just creating a new audit. Think about this case as when cached data is not available, perform a request to database or service to get data and then save it in cache by serialising it to a string and a key constant using the private cache member (as shown on line no. 21).

So, on next request, this value will be available from cache. Also, there are many configuration options that can be used when using cache such as expiry date or time for a cached key, value. In the code above, I’m using a sliding expiry for this cache entry which basically sets how long the cache entry can be inactive (e.g. not accessed) before it will be removed.

Azure Redis Console

Azure portal has a Redis Console that can be used to view all the keys (and values) that are available in the service. This console can be accessed from the Overview area of the Redis Cache service in portal. There are many other Redis console commands available that will work in the Microsoft’s version of Redis console service as well.

This sums up my post that explains how to use Azure Redis Cache with ASP.NET Core application. Please subscribe to my blog and to my Youtube channel to learn more about similar topics. I’ve published about other Microsoft Azure Services that will a good read for you.

Related

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.