Redis client for C# (.NET): StackExchange.Redis

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Redis client for C# (.NET): StackExchange.Redis



In modern .NET platform development, there is often a need for fast data caching, message queue organization, or session management. One of the best solutions for these tasks is using Redis — a high-performance key-value data store. For interacting with Redis from C# (.NET), the most popular and reliable library is StackExchange.Redis.



What is StackExchange.Redis?



StackExchange.Redis is an open-source client library developed by Stack Overflow. It provides a full set of functions for working with Redis: from simple GET/SET operations to complex scenarios with publish/subscribe (Pub/Sub), transactions, and Lua scripts. The library is optimized for multithreaded applications and supports asynchronous operations, making it an ideal choice for high-load services in C#.



Installation



You can install the library via NuGet Package Manager. Run the command in the Package Manager Console:



Install-Package StackExchange.Redis


Or via .NET CLI:



dotnet add package StackExchange.Redis


After installation, you can connect to the Redis server using a connection string:



using StackExchange.Redis;

ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379");IDatabase db = redis.GetDatabase();


Main features and code examples



1. Basic key operations



The most common scenario is saving and retrieving values. Example of working with strings:



// Writing datadb.StringSet("user:1:name", "Alexey");db.StringSet("user:1:email", "alex@example.com");

// Reading datastring name = db.StringGet("user:1:name");string email = db.StringGet("user:1:email");

Console.WriteLine($"Name: {name}, Email: {email}");


2. Working with hashes



Redis supports the "hash" data structure, which is convenient for storing objects:



// Writing a hashHashEntry[] user = new HashEntry[]{    new HashEntry("name", "Maria"),    new HashEntry("age", 28),    new HashEntry("city", "Moscow")};db.HashSet("user:2", user);

// Reading all fieldsHashEntry[] loadedUser = db.HashGetAll("user:2");foreach (var entry in loadedUser){ Console.WriteLine($"{entry.Name}: {entry.Value}");}


3. Caching with time-to-live



One of the key features of Redis is automatic deletion of outdated data. Set a TTL (Time To Live) for a key:



// Cache data for 10 minutesdb.StringSet("cache:weather", "sunny, +22°C", TimeSpan.FromMinutes(10));

// Check time-to-liveTimeSpan? ttl = db.KeyTimeToLive("cache:weather");Console.WriteLine($"Remaining: {ttl?.TotalSeconds} seconds");


4. Publish and subscribe (Pub/Sub)



Implement real-time message exchange. Example of a subscriber:



// Create a subscriberISubscriber subscriber = redis.GetSubscriber();subscriber.Subscribe("notifications", (channel, message) =>{    Console.WriteLine($"Notification received: {message}");});

// Publish a messagesubscriber.Publish("notifications", "Hello, world!");


5. Transactions



Execute multiple operations atomically:



ITransaction transaction = db.CreateTransaction();transaction.AddCondition(Condition.KeyNotExists("counter:lock"));transaction.StringSetAsync("counter:lock", "1");transaction.StringIncrementAsync("counter:value");

// Commit the transactionbool committed = transaction.Execute();Console.WriteLine(committed ? "Transaction committed" : "Aborted");


Advantages of StackExchange.Redis



Recommendations