How To Use Azure Redis Cache In C#

Azure Redis Cache is based on Redis Cache. Redis cache is an open source, in-memory database that is used for improving the performance of an application by retrieving and storing the data in Redis cache using Key-value format. In this article, we will learn step-by-step how to use Azure Redis Cache in Azure.

Introduction

Azure Redis Cache is based on open source, in-memory Redis Cache that allows Web apps to bring data from a backend data source into cache and server Web pages from the cache to improve app performance. In this step by step tutorial, we will learn how to use Azure Redis Cache in our Web app.

What is Azure Redis Cache

Modern applications mostly work with a large amount of data. In this scenario, when you retrieve data from a database, it typically finds the table and gets the results that it sends back to the user. The performance, in such case, goes down due to multiple requests. So, to reduce some number of requests, you can use cache data that does not change frequently.

Redis Cache is an open source, in-memory database that is used for improving the performance of an application by retrieving and storing the data in the cache memory using a Key-value format. Azure Redis Cache is a feature-rich functionality that gives you access to secure, low-latency, high-performance throughput.

Let’s start Redis Cache implementation with C#.

Step 1

Log into Azure port, go to Databases >> Redis Cache.
 
Azure Redis Cache In C# 

Step 2

Create a news Redis Cache.
 
Azure Redis Cache In C# 

Step 3

Get the Access Keys to connect with the newly created Redis Cache.
 
Azure Redis Cache In C# 

Step 4

Install the StackExchange.Redis NuGet package using the following command. 
 
Install-Package StackExchange.Redis 
 
Azure Redis Cache In C# 

Let’s start coding to store the data into Redis Cache and retrieve the data from Redis Cache. We had recently seen the code of Azure Document DB CRUD operations. If you have not read it yet, click on Azure Document DB CRUD Operation and read. We have the code of CRUD operations in Document DB. Now, we will implement Redis Cache here.

Step 5
 
Similar to the previous article, we need to add Redis Cache connection string into the appsettings.dev.json file.
 
Azure Redis Cache In C# 

Step 6
 
Now, add one more property RedisCache into Config.cs that will get the value of Redis Cache connection string from appsettings.dev.json.
  1. public class Config  
  2.  {  
  3.      public DocDbConnectionString docDb { get; set; }  
  4.      public string RedisCache { get; set; }  
  5.  }  
  6.  public class DocDbConnectionString  
  7.  {  
  8.      public string EndPoint { get; set; }  
  9.      public string AuthKey { get; set; }  
  10.      public string Database { get; set; }  
  11.      public string Collection { get; set; }  
  12.  }  

Step 7

Let’s come to the program.cs file and add ConnectionMultiplexer for Redis Cache.
  1. IDatabase cache = lazyConnection.Value.GetDatabase();  
  2. private static Lazy<ConnectionMultiplexer> lazyConnection = new    Lazy<ConnectionMultiplexer>(() =>  
  3.         {  
  4.             string cacheConnection = configs.RedisCache;  
  5.             return ConnectionMultiplexer.Connect(cacheConnection);  
  6.         });  
  7.   
  8.         public static ConnectionMultiplexer Connection  
  9.         {  
  10.             get  
  11.             {  
  12.                 return lazyConnection.Value;  
  13.             }  
  14.         }  

Step 7

Now, we will store a document into Redis Cache on the basis of Key while creating a document into Document DB and while reading this document, we will use the Key to check if the document is present in Redis Cache or not. We will skip reading the document further from Document DB. By doing this, we can increase the performance of the application.
  1. var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);  
  2.             try  
  3.             {  
  4.                 // create jobject which contain the employee details  
  5.                 Console.WriteLine("\nCreating document");  
  6.                 JObject emp = new JObject();  
  7.                 emp.Add("id""V003");  
  8.                 emp.Add("name""virendra");  
  9.                 emp.Add("address""Indore");  
  10.                 emp.Add("Country""India");  
  11.   
  12.                 // create the document into DocumentDb  
  13.                 var createResponse = await Client.CreateDocumentAsync(collection, emp);  
  14.                 var createdDocument = createResponse.Resource;  
  15.   
  16.                Console.WriteLine("Document with id {0} created", createdDocument.Id);  
  17.              //Set JObject into redis cache with key "redisEmp3"  
  18.               var entryInRedis = await cache.StringSetAsync("redisEmp3", emp.ToString());  
  19.               Console.WriteLine("Document with key redisEmp3 stored into redis cache");  
  20.             }  
  21.             catch (Exception ex)  
  22.             {  
  23.                 throw ex;  
  24.             }  

Step 8

Instead, let us read the document from Redis Cache.
  1.  //Read document from Redis Cache .  
  2.   var empInRedis = await cache.StringGetAsync("redisEmp3");  
  3.   if (!empInRedis.IsNullOrEmpty)  
  4.   {  
  5.       Console.WriteLine("Read Document from RedisCache {0} : ", empInRedis);  
  6.   }  
  7.    
  8. //If Redis Cache does not has Document, then read the document from Document DB  
  9.   if (empInRedis.IsNullOrEmpty)  
  10.   {  
  11.                       var readResponse = await        client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));  
  12.       var readDocument = readResponse.Resource;  
  13.       Console.WriteLine("Read Document {0}: ", readResponse.Resource.ToString());  
  14.   }  

The below snapshot shows how we read a document from Redis Cache.

Azure Redis Cache In C# 

Step 10

The following is the whole code of the Program.cs class.
  1. class Program  
  2.     {  
  3.         private static IConfiguration Configuration { get; set; }  
  4.         private static Config configs;  
  5.         private DocumentClient client;  
  6.         IDatabase cache = lazyConnection.Value.GetDatabase();  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // Set up Configuration  
  10.             var builder = new ConfigurationBuilder()  
  11.                 .SetBasePath(Directory.GetCurrentDirectory())  
  12.                 .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: false, reloadOnChange: true);  
  13.             Configuration = builder.Build();  
  14.             configs = new Config();  
  15.             Configuration.Bind(configs);  
  16.   
  17.             Program obj = new Program();  
  18.             obj.CRUDOperation().Wait();  
  19.   
  20.         }  
  21.         //CRUD Operation  
  22.         private async Task CRUDOperation()  
  23.         {  
  24.             var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);  
  25.             try  
  26.             {  
  27.                 // create jobject which contain the employee details  
  28.                 Console.WriteLine("\nCreating document");  
  29.                 JObject emp = new JObject();  
  30.                 emp.Add("id""V003");  
  31.                 emp.Add("name""virendra");  
  32.                 emp.Add("address""Indore");  
  33.                 emp.Add("Country""India");  
  34.                 // create the document  
  35.                 var createResponse = await Client.CreateDocumentAsync(collection, emp);  
  36.                 var createdDocument = createResponse.Resource;  
  37.   
  38.                 Console.WriteLine("Document with id {0} created", createdDocument.Id);  
  39.                 //Set JObject into redis cache with key "redisEmp3"  
  40.                 var entryInRedis = await cache.StringSetAsync("redisEmp3", emp.ToString());  
  41.                 Console.WriteLine("Document with key redisEmp3 stored into redis cache");  
  42.             }  
  43.             catch (Exception ex)  
  44.             {  
  45.                 throw ex;  
  46.             }  
  47.             //read document from redis cache .  
  48.             var empInRedis = await cache.StringGetAsync("redisEmp3");  
  49.             if (!empInRedis.IsNullOrEmpty)  
  50.             {  
  51.                 Console.WriteLine("Read Document from RedisCache {0} : ", empInRedis);  
  52.             }  
  53.             if (empInRedis.IsNullOrEmpty)  
  54.             {  
  55.                 //Read document from document Db  
  56.                 var readResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));  
  57.                 var readDocument = readResponse.Resource;  
  58.                 Console.WriteLine("Read Document {0}: ", readResponse.Resource.ToString());  
  59.             }  
  60.   
  61.         }  
  62.   
  63.         //Get a single instance of Document client and reuse  
  64.         public DocumentClient Client  
  65.         {  
  66.             get  
  67.             {  
  68.                 if (client == null)  
  69.                 {  
  70.                     Uri endpointUri = new Uri(configs.docDb.EndPoint);  
  71.                     client = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);  
  72.                     client.OpenAsync();  
  73.                 }  
  74.                 return client;  
  75.             }  
  76.         }  
  77.         //To establish Redis Cache connection  
  78.         private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>  
  79.         {  
  80.             string cacheConnection = configs.RedisCache;  
  81.             return ConnectionMultiplexer.Connect(cacheConnection);  
  82.         });  
  83.   
  84.         public static ConnectionMultiplexer Connection  
  85.         {  
  86.             get  
  87.             {  
  88.                 return lazyConnection.Value;  
  89.             }  
  90.         }  
  91.     }  

I hope this article will help you!