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:
- 64 bit OS
- 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:
- 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:
- 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 project RedisConnectionTest:
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:
- public class RedisConnectorHelper
- {
- static RedisConnectorHelper()
- {
- RedisConnectorHelper.lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
- {
- return ConnectionMultiplexer.Connect("localhost");
- });
- }
-
- private static Lazy<ConnectionMultiplexer> lazyConnection;
-
- public static ConnectionMultiplexer Connection
- {
- get
- {
- return lazyConnection.Value;
- }
- }
- }
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 a 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
- class Program
- {
- static void Main(string[] args)
- {
- var program = new Program();
-
- Console.WriteLine("Saving random data in cache");
- program.SaveBigData();
-
- Console.WriteLine("Reading data from cache");
- program.ReadData();
-
- Console.ReadLine();
- }
-
- public void ReadData()
- {
- var cache = RedisConnectorHelper.Connection.GetDatabase();
- var devicesCount = 10000;
- for (int i = 0; i < devicesCount; i++)
- {
- var value = cache.StringGet($"Device_Status:{i}");
- Console.WriteLine($"Valor={value}");
- }
- }
-
- public void SaveBigData()
- {
- var devicesCount = 10000;
- var rnd = new Random();
- var cache = RedisConnectorHelper.Connection.GetDatabase();
-
- for (int i = 1; i < devicesCount; i++)
- {
- var value = rnd.Next(0, 10000);
- cache.StringSet($"Device_Status:{i}", value);
- }
- }
- }
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 will 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.