joydip_kanjilal
Contributor

How to work with Redis Cache in .NET

how-to
Apr 05, 20174 mins
Microsoft .NETSoftware Development

Redis is an open source, fast, feature rich, in-memory caching engine that can be used to store and retrieve data in your applications

Caching is a state management strategy that can be used to improve the performance of your applications as it helps you to reduce the consumption of resources in your system.

Redis Cache is an open source, high-speed, NoSQL database. It’s fast, and it runs entirely in memory with negligible performance overhead when reading and writing data. It should be noted that Redis is free for both commercial and non-commercial use under the BSD license.

What is Redis Cache and why should I use it?

Redis is one of the most popular open source, NoSQL, in-memory based data stores available. It’s an in-memory data store that can support a wide variety of data structures, i.e., strings, hashes, sets, lists, etc. Redis also provides built-in support for replication and transactions, as well as excellent support for data persistence.

Redis is a good choice primarily if your application needs to store and retrieve a huge amount of data. If your application needs to store and retrieve lots of data and availability of free memory is not a constraint, Redis Cache is the caching engine you should go for. Setting up Redis is quite simple — the sections that follow discuss how to install, configure and use Redis.

Installing Redis

You can download a copy of Redis Cache from GitHub. While installing Redis, you should check the option to add Redis to the PATH environmental variable. Once Redis Cache is installed in your system, you can type Run -> service.msc to see the Redis service running in your system.

Working with the C# Redis client

Now that Redis has been installed in your system, you need a client to store and retrieve data to and from Redis Cache. In this example, we’ll use the ServiceStack C# Redis open source client. To do this, create a new console application project in Visual Studio. You can install ServiceStack.Redis via the NuGet package manager.

Assuming that ServiceStack.Redis has been installed via NuGet, the following two methods illustrate how you can store and retrieve data from the Redis Cache using the ServiceStack.Redis API.

private static bool Save(string host, string key, string value)
        {
            bool isSuccess = false;
            using (RedisClient redisClient = new RedisClient(host))
            {
                if (redisClient.Get<string>(key) == null)
                {
                    isSuccess = redisClient.Set(key, value);
                }
            }
            return isSuccess;
        }
        private static string Get(string host, string key)
        {
            using (RedisClient redisClient = new RedisClient(host))
            {
                return redisClient.Get<string>(key);
            }
        }

Note how the Set and Get methods of RedisClient class have been used to store and retrieve data to and from Redis Cache. I leave it to you to update these two methods to make them generic so that they can work with any type.

Here is how you can call these methods from the Main method:

static void Main(string[] args)
        {
            string host = "localhost";
            string key = "IDG";
            // Store data in the cache
            bool success = Save(host, key, "Hello World!");
            // Retrieve data from the cache using the key
            Console.WriteLine("Data retrieved from Redis Cache: " + Get(host,key));
            Console.Read();
        }

As I said earlier, Redis is feature rich. In one of my future articles here, I will discuss some advanced concepts like persistence, pub-sub, automatic failover, etc. You can take advantage of the RDB (a single compact file) or AOF way of persistence. However, you need to consider the trade-offs between performance, durability, and the disk I/O before you choose the right persistence option.

You can learn more about Redis from the project’s online documentation.

If you’re interested in using a GUI admin tool to view your Redis data, you can try the Redis Admin UI tool.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author