How to use Azure Redis Cache in C#

Take advantage of the distributed, low-latency Azure Redis Cache to scale your .Net application beyond limits

How to use Azure Redis Cache in C#

Redis is an open source, feature rich, in-memory database and caching engine that can be used to store and retrieve data in your applications. Azure Redis Cache is based on this popular database, providing a powerful and secure way to cache your application’s data in the Azure cloud.

Azure Redis Cache is a distributed cache service that can be used to share data across instances and applications running in Azure. You can use Azure Redis Cache in .Net, ASP.Net, Java, Node.js, and Python. In this article we will examine how we can work with Azure Redis Cache in C#.

First off, you should create an Azure account if you don’t have one. You can then follow the steps outlined here to create and configure Redis Cache in Azure.

Install the StackExchange.Redis client

Assuming you are all set to use Azure Redis Cache, it’s finally time for coding. Create a Console Application project in Visual Studio and then install the popular Redis client for .Net called StackExchange.Redis via the NuGet Package Manager UI. Alternatively, you can install this package from the NuGet Package Manager Console using the following command.

Install-Package StackExchange.Redis

To work with the StackExchange.Redis library, you should add the following statement in your program.

using StackExchange.Redis;

To connect to Azure Redis Cache, you need to take advantage of the ConnectionMultiplexer class available as part of the StackExchange.Redis library. Note that you should share an instance of this class and reuse it throughout your application rather than create a connection instance for each operation.

Establish a connection to Azure Redis Cache

The following code snippet illustrates how you can use the static Connect method of the ConnectionMultiplexer class to establish a connection to Azure Redis Cache.

private static ConnectionMultiplexer GetConnection()
            string connectionString =",password=somepwd,ssl=True,abortConnect=False";
            return ConnectionMultiplexer.Connect(connectionString);

Once a connection has been established, you can take advantage of the GetDatabase method of the ConnectionMultiplexer class to connect to the database inside Azure Redis Cache.

IDatabase redisCache = GetConnection().GetDatabase();

Store and retrieve objects from Azure Redis Cache

You can add or retrieve objects to and from the cache using the StringSet and StringGet methods respectively. The following code snippet illustrates how these methods can be used.

redisCache.StringSet(“myKey”, “myValue”);
string data = redisCache.StringGet(“myKey”);

Note that both of these methods have their async counterparts, the StringSetAsync and StringSetAsync methods. Redis supports a range of data types. The supported data types include Strings, Lists, Sets, Hashes, Sorted sets, Bitmaps, and HyperLogLogs. If you want to learn more about the supported data types in Redis, check out this page of the Redis documentation.

When retrieving data from the cache, you may also want to use RedisValue. RedisValue has implicit operators that help you work with integral data types. Here is an example that illustrates how RedisValue can be used.

RedisValue data = redisCache.StringGet(“myKey”);
if (data.HasValue)
    redisCache.StringSet(“myKey”, “myValue”); 

Store .Net CLR objects in Azure Redis Cache

You can store .Net CLR objects in Redis but it is imperative that you serialize the object before storing it. The choice of the serializer is up to you, but a serialization framework preferred by many is Json.Net from Newtonsoft.

Consider the following class.

public class Author
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Author(int id, string firstName, string lastName)
            this.Id = id;
            this.FirstName = firstName;
            this.LastName = lastName;

You can use the following code snippet to store an Author instance to the cache.

redisCache.StringSet(“A001”, JsonConvert.SerializeObject(new Author(1, “Joydip”, “Kanjilal”)));

To retrieve a previously stored instance from the cache, you can use the following code.

Author author = JsonConvert.DeserializeObject<Author>(redisCache.StringGet(“A001”));

Azure Redis Cache is available in three tiers—Basic, Standard, and Premium—with varied cache storage capacities and pricing. In the Basic and Standard tiers, data is stored in the memory of the virtual machine instance where the Redis service has been provisioned. If you want to persist the cached data to storage, then you will need to use the Premium tier. Only the Premium tier of Azure Redis Cache supports data persistence.

Although Redis is primarily used to cache data, it is a flexible data store that can serve many purposes. You could even use Azure Redis Cache as a pub/sub messaging system. I will discuss this use of Redis in a later post here.

Copyright © 2018 IDG Communications, Inc.