.net, Redis

Creating a simple Redis manager in .NET Core (using environment variables to connect)

I’ve been interested in using caching to improve the performance of my .NET applications, and I decided to try out the Redis NoSQL server. This post is about how I started (from a point of knowing nothing about Redis or how to use it), up to the point where I was able to read and write values through a .NET Core application.

Step 1: Installing Redis

I downloaded the latest installer for the Windows version of Redis from here. (You should read the information on this site to determine the if this is best version for you).

screenshot-1479416567

This is a fairly simple and straightforward installer – there were a few decision points, such as adding the installation directory to the machine’s path

:screenshot-1479416592

Also you can choose which port that Redis runs on – 6379 is usually used for non-SSL access, or 6380 for SSL.

screenshot-1479416596

This process will also install a Windows service for the Redis database.

screenshot-1479417295

Step 2: Create an environment variable to connect to Redis

The simplest connection string is really simple – it’s just “localhost”. So I’ll create an environment variable called “REDIS_CONNECTIONSTRING” with this value. I’ve previously written about this technique.

[Environment]::SetEnvironmentVariable("REDIS_CONNECTIONSTRING", "localhost", "Machine")

Step 3: Create the .NET Core project and class to connect to Redis

First we simply create a new .NET Core project – I’ve called mine RedisAPI.
screenshot-1479419418

Once this project is created, I need to add a couple of libraries – the StackExchange.Redis library, and Microsoft.Extensions.Configuration.EnvironmentVariables. I added these in the project.json file using the code below, and restored the packages using “dotnet restore”.

"dependencies": {
  "NETStandard.Library": "1.6.0",
  "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc1-final",
  "StackExchange.Redis": "1.1.608"
}

The next step is to add a class that connects to the Redis NoSQL instance running on my machine. I found a post from another .NET Engineer, Alwyn Thomas, which creates a RedisConnectionFactory – he explains more about this here. I adjusted his RedisConnectionFactory to pull the Redis connection string from the machine’s environment variables (rather than from application config).

using Microsoft.Extensions.Configuration;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
 
namespace RedisAPI
{
    public class RedisConnectionFactory
    {
        private static readonly Lazy<ConnectionMultiplexer> Connection;
 
        private static readonly string REDIS_CONNECTIONSTRING = "REDIS_CONNECTIONSTRING";
 
        static RedisConnectionFactory()
        {
            var config = new ConfigurationBuilder()
                .AddEnvironmentVariables()
                .Build();
 
            var connectionString = config[REDIS_CONNECTIONSTRING];
 
            if (connectionString == null)
            {
                throw new KeyNotFoundException($"Environment variable for {REDIS_CONNECTIONSTRING} was not found.");
            }
 
            var options = ConfigurationOptions.Parse(connectionString);
 
            Connection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(options));
        }
 
        public static ConnectionMultiplexer GetConnection() => Connection.Value;
    }
}

Now that I have a connection factory, it’s very simple to create a class which acts as an agent to allow me to read, write and delete string values from the Redis database.

using StackExchange.Redis;
 
namespace RedisAPI
{
    public class RedisDataAgent
    {
        private static IDatabase _database;
        public RedisDataAgent()
        {
            var connection = RedisConnectionFactory.GetConnection();
 
            _database = connection.GetDatabase();
        }
 
        public string GetStringValue(string key)
        {
            return _database.StringGet(key);
        }
 
        public void SetStringValue(string key, string value)
        {
            _database.StringSet(key, value);
        }
 
        public void DeleteStringValue(string key)
        {
            _database.KeyDelete(key);
        }
    }
}

Finally I can demonstrate how to use this by creating a console .NET Core app and reference this project – the class below shows how.

using RedisAPI;
 
namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string inputStringData = "hello world";
 
            var dataAgent = new RedisDataAgent();
 
            dataAgent.SetStringValue("cachedVariable", inputStringData);
            
            // returns "hello world"
            string s = dataAgent.GetStringValue("cachedVariable");
        }
    }
}

Obviously there is a lot more to Redis than the simple use case I’ve described here – but hopefully this is enough to get started with how to use it to cache data in .NET Core, and configure it using Windows environment variables.