Introduction
Redis is a fast, in-memory key-value store widely used for caching, session storage, message brokering, and pub/sub communication in modern applications. It’s lightweight, performant, and developer-friendly, making it a go-to choice for building scalable systems.
If you're developing in .NET Core and want to integrate Redis into your application, this article will show you how to use the StackExchange.Redis library to perform basic Redis operations.
For those working on Windows systems, a Redis-compatible server can be used to run Redis without needing Linux or containerization.
Why Redis?
Redis offers several benefits when integrated with a .NET Core application.
- Caching: Store frequently accessed data to improve response times and reduce database workloads.
- Session Management: Handle user sessions efficiently in distributed systems.
- Real-Time Events: Use Redis for pub/sub features to power real-time functionality like notifications or event-driven communication.
- High Performance: Operates in memory, offering low-latency data access.
- Scalable: With support for clustering and sharding, Redis is built for scalability.
Setting Up Redis
Using Redis
To connect your .NET Core app to Redis, you can run Redis either.
- Command-Line Installation: Use tools like Docker to run Redis on Linux or Windows.
- Pre-Configured Windows Alternative: If you’re on Windows, you can use a Redis-compatible server as a drop-in replacement for running Redis natively.
Note. For simplicity, this tutorial assumes Redis is running locally on localhost:6379.
Building a .NET Core Application with Redis
In this example, we’ll create a .NET Core console application that performs the following Redis operations.
- Connect to a Redis server.
- Perform basic key-value operations (set, get, delete).
- Demonstrate key expiration and validation.
Step 1. Create the .NET Core Project.
-
Open a terminal and create a new project.
dotnet new RedisIntegrationDemo
-
Install the StackExchange.Redis package for Redis connectivity.
dotnet add package StackExchange.Redis
Step 2. Write the Code.
Here’s the full implementation in the Program.cs.
using System;
using StackExchange.Redis;
using System.Threading.Tasks;
namespace RedisIntegrationDemo
{
class Program
{
// Connection string for Redis
private const string RedisConnectionString = "localhost:6379";
async static Task Main(string[] args)
{
Console.WriteLine("Connecting to Redis...");
// Connect to Redis
var redis = await ConnectionMultiplexer.ConnectAsync(RedisConnectionString);
Console.WriteLine("Connected to Redis successfully.\n");
// Access the Redis database
IDatabase db = redis.GetDatabase();
// Perform Redis operations
Console.WriteLine("Performing Redis operations...");
// 1. Set key-value pair
string key = "SampleKey";
string value = "Hello from Redis!";
await db.StringSetAsync(key, value);
Console.WriteLine($"Set: {key} => {value}");
// 2. Get the value for the key
string savedValue = await db.StringGetAsync(key);
Console.WriteLine($"Get: {key} => {savedValue}");
// 3. Set an expiration for the key
TimeSpan expiryTime = TimeSpan.FromSeconds(10);
await db.KeyExpireAsync(key, expiryTime);
Console.WriteLine($"Set expiration for {key}: {expiryTime.TotalSeconds} seconds");
// 4. Check key existence after expiration
Console.WriteLine("\nWaiting for the key to expire...");
await Task.Delay(12000); // Wait 12 seconds
bool exists = await db.KeyExistsAsync(key);
Console.WriteLine($"Key Exists After Expiration: {key} => {exists}");
// Close the connection
redis.Close();
Console.WriteLine("\nAll Redis operations completed.");
}
}
}
Step 3. Run the Application.
To execute the application.
dotnet run
Expected Output
The program will connect to Redis, perform basic key-value operations, and validate key expiration. You should see output like this,
![Output]()
How Redis Works with .NET Core?
Here’s what the application does step by step,
- Connects to the Redis server using ConnectionMultiplexer, which manages connection pooling and server communication.
- Performs basic commands.
- StringSetAsync: Sets a key-value pair in Redis.
- StringGetAsync: Gets the value of a key.
- KeyExpireAsync: Sets an expiration time for a key.
- KeyExistsAsync: Checks if a key exists.
- Handles temporary in-memory storage of data with expiration.
If you’re working in a Windows environment and prefer not to install a native Redis instance or use Docker, you can use a Redis-compatible server as an alternative.
Setting Up a Redis-Compatible Server
- Install a Redis-compatible server for Windows.
- Once installed, the server typically runs on localhost:6379 by default, similar to Redis.
- Your application does not require any code changes to work with a Redis-compatible server.
Using a Redis-compatible server allows Redis functionality to run natively on Windows without relying on containers or virtualized environments.
Advantages of Using Redis in .NET Core
- Performance: Redis operates fully in memory, enabling extremely low latency.
- Ease of Use: Simplified API for common key-value needs, with additional data structures like lists, sets, and hashes.
- Flexibility: Redis serves multiple purposes (e.g., caching, message queues, pub/sub).
- Scalability: Redis supports clustering and high availability for scaling with demand.
Conclusion
Integrating Redis into your .NET Core application allows you to build high-quality, performant systems that can handle demanding workloads. With the StackExchange.Redis library, you can interact with Redis seamlessly.
Start by implementing Redis for simple caching or session management, and expand its usage to pub/sub and real-time data needs in your distributed .NET Core applications.
Happy coding and scaling!