Giới thiệu
Redis là một fast, in-memory key-value store được dùng rộng rãi cho caching, session storage, message brokering, và pub/sub communication trong modern applications. Nó lightweight, performant, và developer-friendly, làm nó trở thành lựa chọn go-to cho building scalable systems.
Nếu bạn đang develop trong .NET Core và muốn tích hợp Redis vào ứng dụng, bài viết này sẽ chỉ cho bạn cách dùng StackExchange.Redis library để thực hiện basic Redis operations.
Cho những ai làm việc trên Windows systems, một Redis-compatible server có thể dùng để chạy Redis mà không cần Linux hay containerization.
Tại sao Redis?
Redis mang lại nhiều benefits khi tích hợp với .NET Core application.
- Caching: Lưu trữ dữ liệu thường truy cập để cải thiện response times và giảm database workloads.
- Session Management: Xử lý user sessions hiệu quả trong distributed systems.
- Real-Time Events: Dùng Redis cho pub/sub features để power real-time functionality như notifications hoặc event-driven communication.
- High Performance: Hoạt động trong memory, cung cấp low-latency data access.
- Scalable: Với support cho clustering và sharding, Redis built for scalability.
Setting Up Redis
Using Redis
Để connect .NET Core app đến Redis, bạn có thể chạy Redis either.
- Command-Line Installation: Dùng tools như Docker để chạy Redis trên Linux hoặc Windows.
- Pre-Configured Windows Alternative: Nếu bạn trên Windows, bạn có thể dùng Redis-compatible server như drop-in replacement để chạy Redis native.
Note. Để đơn giản, tutorial này giả định Redis chạy locally trên localhost:6379.
Building a .NET Core Application với Redis
Trong ví dụ này, chúng ta sẽ tạo .NET Core console application thực hiện các Redis operations sau.
- Connect đến Redis server.
- Thực hiện basic key-value operations (set, get, delete).
- Demo key expiration và validation.
Step 1. Tạo .NET Core Project.
Mở terminal và tạo project mới.
dotnet new RedisIntegrationDemoCài đặt StackExchange.Redis package cho Redis connectivity.
dotnet add package StackExchange.Redis
Step 2. Viết Code.
Đây là full implementation trong Program.cs.
using System;
using StackExchange.Redis;
using System.Threading.Tasks;
namespace RedisIntegrationDemo {
class Program {
// Connection string cho 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.
Để execute the application.
dotnet run
Expected Output
Program sẽ connect to Redis, perform basic key-value operations, và validate key expiration. Bạn sẽ thấy output như này,

How Redis Works with .NET Core?
Đây là những gì application làm step by step,
- Connects to Redis server dùng ConnectionMultiplexer, quản lý connection pooling và server communication.
- Thực hiện 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 của data với expiration.
Nếu bạn làm việc trong Windows environment và thích không cài native Redis instance hoặc dùng Docker, bạn có thể dùng Redis-compatible server như alternative.
Setting Up a Redis-Compatible Server
- Cài đặt Redis-compatible server cho Windows.
- Sau khi cài, server thường chạy trên localhost:6379 by default, tương tự Redis.
- Application của bạn không cần code changes để làm việc với Redis-compatible server.
Dùng Redis-compatible server cho phép Redis functionality chạy native trên Windows mà không rely vào containers hoặc virtualized environments.
Advantages của Using Redis in .NET Core
- Performance: Redis hoạt động fully in memory, enabling extremely low latency.
- Ease of Use: Simplified API cho common key-value needs, với additional data structures như lists, sets, và hashes.
- Flexibility: Redis phục vụ multiple purposes (ví dụ: caching, message queues, pub/sub).
- Scalability: Redis supports clustering và high availability cho scaling with demand.
Kết luận
Tích hợp Redis vào .NET Core application cho phép bạn build high-quality, performant systems có thể handle demanding workloads. Với StackExchange.Redis library, bạn có thể interact với Redis seamlessly.
Bắt đầu bằng việc implement Redis cho simple caching hoặc session management, và mở rộng usage cho pub/sub và real-time data needs trong distributed .NET Core applications của bạn.
Happy coding và scaling!