How To Use Azure Redis Cache In C#?
Introduction
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 a 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
Step 2
Step 3
Step 4
Let’s start coding to store the data into Redis Cache and retrieve the data from Redis Cache. We have the code of CRUD operations in Document DB. Now, we will implement Redis Cache here.
Step 6
Step 7
IDatabase cache = lazyConnection.Value.GetDatabase();
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
string cacheConnection = configs.RedisCache;
return ConnectionMultiplexer.Connect(cacheConnection);
});
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
Step 7
var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
try
{
// create jobject which contain the employee details
Console.WriteLine("\nCreating document");
JObject emp = new JObject();
emp.Add("id", "V003");
emp.Add("name", "virendra");
emp.Add("address", "Indore");
emp.Add("Country", "India");
// create the document into DocumentDb
var createResponse = await Client.CreateDocumentAsync(collection, emp);
var createdDocument = createResponse.Resource;
Console.WriteLine("Document with id {0} created", createdDocument.Id);
//Set JObject into redis cache with key "redisEmp3"
var entryInRedis = await cache.StringSetAsync("redisEmp3", emp.ToString());
Console.WriteLine("Document with key redisEmp3 stored into redis cache");
}
catch (Exception ex)
{
throw ex;
}
Step 8
//Read document from Redis Cache .
var empInRedis = await cache.StringGetAsync("redisEmp3");
if (!empInRedis.IsNullOrEmpty)
{
Console.WriteLine("Read Document from RedisCache {0} : ", empInRedis);
}
//If Redis Cache does not has Document, then read the document from Document DB
if (empInRedis.IsNullOrEmpty)
{
var readResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
var readDocument = readResponse.Resource;
Console.WriteLine("Read Document {0}: ", readResponse.Resource.ToString());
}
The below snapshot shows how we read a document from Redis Cache.
Step 10
class Program
{
private static IConfiguration Configuration { get; set; }
private static Config configs;
private DocumentClient client;
IDatabase cache = lazyConnection.Value.GetDatabase();
static void Main(string[] args)
{
// Set up Configuration
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: false, reloadOnChange: true);
Configuration = builder.Build();
configs = new Config();
Configuration.Bind(configs);
Program obj = new Program();
obj.CRUDOperation().Wait();
}
//CRUD Operation
private async Task CRUDOperation()
{
var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
try
{
// create jobject which contain the employee details
Console.WriteLine("\nCreating document");
JObject emp = new JObject();
emp.Add("id", "V003");
emp.Add("name", "virendra");
emp.Add("address", "Indore");
emp.Add("Country", "India");
// create the document
var createResponse = await Client.CreateDocumentAsync(collection, emp);
var createdDocument = createResponse.Resource;
Console.WriteLine("Document with id {0} created", createdDocument.Id);
//Set JObject into redis cache with key "redisEmp3"
var entryInRedis = await cache.StringSetAsync("redisEmp3", emp.ToString());
Console.WriteLine("Document with key redisEmp3 stored into redis cache");
}
catch (Exception ex)
{
throw ex;
}
//read document from redis cache .
var empInRedis = await cache.StringGetAsync("redisEmp3");
if (!empInRedis.IsNullOrEmpty)
{
Console.WriteLine("Read Document from RedisCache {0} : ", empInRedis);
}
if (empInRedis.IsNullOrEmpty)
{
//Read document from document Db
var readResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
var readDocument = readResponse.Resource;
Console.WriteLine("Read Document {0}: ", readResponse.Resource.ToString());
}
}
//Get a single instance of Document client and reuse
public DocumentClient Client
{
get
{
if (client == null)
{
Uri endpointUri = new Uri(configs.docDb.EndPoint);
client = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);
client.OpenAsync();
}
return client;
}
}
//To establish Redis Cache connection
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
string cacheConnection = configs.RedisCache;
return ConnectionMultiplexer.Connect(cacheConnection);
});
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
}
I hope this article will help you!