Using REDIS Cache with C#

Introduction

In this article we are going to learn something simple but useful as an introduction to this NoSQL technologies., in this case a key-value NoSQL type. See this article for more information about different types of NoSQL databases.
 
Redis is a NoSQL key-value cache that stores the information in a hash table format, providing the possibilities to store different types of structured data like strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs.

Installing REDIS on Windows

Officially Redis doesn't have an official version for windows, but being an open source project, there is a fork by MSOpenTech where there is the possibility of running Redis on Windows.
 
 Requirements to install Redis:
  1.  64 bit OS
  2. The windows package manager Chocolatey
In order to install Redis on Windows using Chocolatey, we need to run a simple command with the command prompt (as administrator) and just follow the instructions:
  1. C:\> choco install redis-64  
Once the installation is complete, we can run the redis server instance using the command redis-server.exe. If you have problems running the command and get the error "redis-server is not recognized as an internal...etc" is because chocolatey failed registering the system path variable indicating where redis is. You can fix it with the following command:
  1. SET PATH=%PATH%;"c:\Program Files\Redis"  
Now we can run the redis-server.exe to start our redis instance.

Connecting using C#

I will be using Visual Studio 2015 Community Edition and I'm sure you already have it, if not you can download it from here.

We are going to create a Console Application using .Net 4.5 or higher (this is important) naming the proyect RedisConnectionTest:

console application

Having this empty project, we need a Nuget package that is our connector to redis(StackExchange.Redis). Using the Visual Studio tools, we add this Nuget package:

 
 
Once this package is installed, we are going to create a new class named RedisConnectorHelper.cs. In order to have an easy way to manage our connection to redis, we type the following: 
  1. public class RedisConnectorHelper  
  2. {                  
  3.     static RedisConnectorHelper()  
  4.     {  
  5.         RedisConnectorHelper.lazyConnection = new Lazy<ConnectionMultiplexer>(() =>  
  6.         {  
  7.             return ConnectionMultiplexer.Connect("localhost");  
  8.         });  
  9.     }  
  10.       
  11.     private static Lazy<ConnectionMultiplexer> lazyConnection;          
  12.   
  13.     public static ConnectionMultiplexer Connection  
  14.     {  
  15.         get  
  16.         {  
  17.             return lazyConnection.Value;  
  18.         }  
  19.     }  
  20. }  
The connection to Redis is handled by the ConnectionMultiplexer class. To connect to the redis instance we use the static method ConnectionMultiplexer.Connect, that takes a string parameter with the connection string.

ConnectionMultiplexer
was designed for code sharing by the whole application, is not necessary to create a new instance every time you need a simple operation. Creating a new instance every time we need cache, the performance may be affected. In addition, if we are using Redis cache from Azure, there is a limit connection so if we create a new connection each time we need the cache, this limit can be exceeded.

An easy way to share the Multiplexer instance is using a static property. This class was designed to be used like this, singleton and thread-safe.

Setting and Getting data from the cache
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         var program = new Program();  
  6.   
  7.         Console.WriteLine("Saving random data in cache");  
  8.         program.SaveBigData();  
  9.   
  10.         Console.WriteLine("Reading data from cache");  
  11.         program.ReadData();  
  12.   
  13.         Console.ReadLine();  
  14.     }  
  15.   
  16.     public void ReadData()  
  17.     {  
  18.         var cache = RedisConnectorHelper.Connection.GetDatabase();  
  19.         var devicesCount = 10000;  
  20.         for (int i = 0; i < devicesCount; i++)  
  21.         {  
  22.             var value = cache.StringGet($"Device_Status:{i}");  
  23.             Console.WriteLine($"Valor={value}");  
  24.         }  
  25.     }  
  26.   
  27.     public void SaveBigData()  
  28.     {  
  29.         var devicesCount = 10000;  
  30.         var rnd = new Random();  
  31.         var cache = RedisConnectorHelper.Connection.GetDatabase();  
  32.   
  33.         for (int i = 1; i < devicesCount; i++)  
  34.         {  
  35.             var value = rnd.Next(0, 10000);  
  36.             cache.StringSet($"Device_Status:{i}", value);  
  37.         }  
  38.     }  
  39. }  
With the SaveBigData method we save 10,000 items with random values between 0 and 10,000. The important here is how we use our helper connection class.
 
We use the method GetDatabase from the Multiplexer to access the cache. This instance has too many methods: can read, save, delete, increase data, concatenate and finally, all the commands that Redis has. We use StringSet to save a string (or any primitive type) using the "Device_Status: NUMBER" as a key.
 
Comment the line number 10 and 11 and run the application, you are going to see something similar to this (left window):

 
The operation of Redis is to have everything in memory and depending on certain rules, it will save everything to the hard disk.

To view these random data we just add,  use a totally similar to StringSet method: StringGet.

Uncomment the lines 10-11 and comment the lines 07-08 and run again the console application, you we see the following (left window):

 
This is how we connect to redis using the StackOverflow framework (the nuget package) and get&set some random items to the cache with disk persistence.

Regards and Code4Fun. 

Up Next
    Ebook Download
    View all
    Learn
    View all