How to use Redis Cache in C#

By FoxLearn 1/6/2025 9:32:37 AM   95
Redis is an open-source, high-performance in-memory caching engine, packed with features, that allows you to efficiently store and retrieve data in your applications.

Caching is a state management technique designed to enhance application performance by minimizing resource consumption in your system.

Redis Cache is an open-source, high-performance NoSQL database that operates entirely in memory, offering near-instantaneous data read and write speeds with minimal overhead. Additionally, 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 a popular open-source, in-memory NoSQL data store that supports various data structures like strings, hashes, sets, and lists. It offers features such as replication, transactions, and strong data persistence. Redis is ideal for applications requiring fast storage and retrieval of large amounts of data, especially when memory availability isn't a concern.

To install Redis, download it from GitHub and ensure you select the option to add Redis to the PATH environment variable. After installation, you can check if the Redis service is running by typing "Run -> service.msc" on your system.

Using the C# Redis Client

After installing Redis on your system, you’ll need a client to interact with the Redis Cache.

In this example, we'll use the popular StackExchange.Redis client for C#.

First, create a new console application in Visual Studio, and install the StackExchange.Redis package via the NuGet package manager.

Once StackExchange.Redis is installed, you can use the following methods to store and retrieve data from Redis Cache:

private static bool Save(string host, string key, string value)
{
    bool isSuccess = false;
    try
    {
        using (var redisClient = new RedisClient(host))
        {
            // Check if the key exists already, and set the value only if it doesn't exist
            if (redisClient.Get<string>(key) == RedisValue.Null)
            {
                isSuccess = redisClient.Set(key, value);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error saving data to Redis: " + ex.Message);
    }
    return isSuccess;
}

private static string Get(string host, string key)
{
    try
    {
        using (var redisClient = new RedisClient(host))
        {
            // Return data from Redis, or null if the key does not exist
            var result = redisClient.Get<string>(key);
            return result == RedisValue.Null ? null : result;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error retrieving data from Redis: " + ex.Message);
        return null;
    }
}

The Set and Get methods of the RedisClient class are used to store and retrieve data from Redis Cache. You can modify these methods to make them generic, allowing them to handle different data types beyond just strings.

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

    Console.Read();
}

Redis offers many advanced features, including persistence, pub-sub, and automatic failover. When selecting a persistence option, such as RDB or AOF, it's important to weigh the trade-offs between performance, durability, and disk I/O.