StackExchange.Redis
GitHub Overview
StackExchange/StackExchange.Redis
General purpose redis client
Stars6,084
Watchers306
Forks1,542
Created:March 14, 2014
Language:C#
License:Other
Topics
c-sharpredisredis-client
Star History
Data as of: 10/22/2025, 08:06 AM
Cache Library
StackExchange.Redis
Overview
StackExchange.Redis is a high-performance Redis client library for .NET environments. It provides advanced features such as multiplexed connections, asynchronous operations, and Redis Cluster support, optimized for distributed caching and real-time applications.
Details
StackExchange.Redis is a .NET client library that enables efficient communication with Redis (Remote Dictionary Server). It achieves high performance by minimizing connection overhead through a design that multiplexes a single connection for shared use across multiple threads.
Key Technical Features
- Multiplexed Connections (ConnectionMultiplexer): Logically divides physical connections for efficient use by multiple threads
- Async-First API: Standard support for non-blocking operations using async/await patterns
- Redis Cluster Support: Automatic slot detection and command routing functionality
- Redis Sentinel Integration: Support for automatic failover and high availability configurations
- Pipelining: Communication optimization through batch sending of multiple commands
- Error Recovery: Automatic reconnection and command retry on connection failures
Supported Protocols and Data Types
- RESP2/RESP3 protocol support
- All Redis data types (String, Hash, List, Set, Sorted Set, Stream)
- Pub/Sub (Publish/Subscribe) messaging
- Lua script execution (EVAL/EVALSHA)
- Redis Modules support
Pros and Cons
Pros
- High Performance: Efficient communication through multiplexed connections and pipelining
- Robustness: Equipped with automatic reconnection, error recovery, and backlog system
- Scalability: Support for large-scale distributed environments with Redis Cluster and Sentinel
- Rich Features: Comprehensive support for all Redis functionality
- .NET Integration: Natural integration with Task/async patterns
- Community: High reliability through development and maintenance by Stack Overflow
Cons
- Learning Curve: Requires understanding of Redis itself plus multiplexed architecture
- Configuration Complexity: Complex setup for high availability configurations
- Memory Usage: Memory overhead from connection management and backlog system
- .NET Dependency: Limited to .NET environments with no compatibility with other languages
Reference Links
Code Examples
Basic Connection and Data Operations
using StackExchange.Redis;
// Create connection multiplexer (reuse recommended)
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
// Basic String operations
string value = "Hello Redis";
await db.StringSetAsync("mykey", value);
string result = await db.StringGetAsync("mykey");
Console.WriteLine(result); // "Hello Redis"
// Data with expiration
await db.StringSetAsync("temp_key", "temporary", TimeSpan.FromMinutes(5));
Hash Operations and Pipelining
// Hash operations
await db.HashSetAsync("user:1000", new HashEntry[] {
new("name", "John Doe"),
new("email", "[email protected]"),
new("age", 30)
});
string userName = await db.HashGetAsync("user:1000", "name");
// Pipelining (batch processing)
IBatch batch = db.CreateBatch();
Task<bool> setTask1 = batch.StringSetAsync("key1", "value1");
Task<bool> setTask2 = batch.StringSetAsync("key2", "value2");
Task<long> incrTask = batch.StringIncrementAsync("counter");
batch.Execute();
await Task.WhenAll(setTask1, setTask2, incrTask);
Pub/Sub (Real-time Communication)
// Subscriber side
ISubscriber sub = redis.GetSubscriber();
await sub.SubscribeAsync("notifications", (channel, message) => {
Console.WriteLine($"Received: {message}");
});
// Publisher side
await sub.PublishAsync("notifications", "Hello Subscribers!");
Redis Cluster Connection
// Connection to cluster environment
var options = new ConfigurationOptions {
EndPoints = {
{ "node1.redis.cluster", 7000 },
{ "node2.redis.cluster", 7000 },
{ "node3.redis.cluster", 7000 }
},
CommandMap = CommandMap.Create(new HashSet<string> { "INFO" }, false)
};
ConnectionMultiplexer cluster = ConnectionMultiplexer.Connect(options);
IDatabase clusterDb = cluster.GetDatabase();
// Cluster-aware data operations
await clusterDb.StringSetAsync("cluster_key", "cluster_value");
Lua Script Execution
// Atomic operations using Lua scripts
string luaScript = @"
local current = redis.call('GET', KEYS[1])
if current == false then
redis.call('SET', KEYS[1], ARGV[1])
return 1
end
return 0
";
RedisResult result = await db.ScriptEvaluateAsync(
luaScript,
new RedisKey[] { "atomic_key" },
new RedisValue[] { "new_value" }
);
Configuration and Monitoring
// Detailed configuration options
var configOptions = new ConfigurationOptions {
EndPoints = { "localhost:6379" },
ConnectTimeout = 5000,
SyncTimeout = 5000,
AbortOnConnectFail = false,
ConnectRetry = 3,
KeepAlive = 60
};
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(configOptions);
// Connection status and metrics monitoring
Console.WriteLine($"Is Connected: {redis.IsConnected}");
Console.WriteLine($"Operation Count: {redis.OperationCount}");
Console.WriteLine($"Configuration: {redis.Configuration}");
// Server information retrieval
IServer server = redis.GetServer("localhost", 6379);
DateTime lastSave = server.LastSave();
ClientInfo[] clients = server.ClientList();