Redis là kho lưu trữ dữ liệu trong bộ nhớ, hiệu suất cao được sử dụng rộng rãi để lưu vào bộ nhớ đệm, quản lý phiên, phân tích thời gian thực, v.v. Trong hướng dẫn này, chúng ta sẽ khám phá cách tích hợp Redis với ứng dụng .NET bằng StackExchange.Redis , một trong những ứng dụng khách Redis phổ biến nhất cho .NET.
1. Điều kiện tiên quyết
Trước khi bắt đầu, hãy đảm bảo bạn có:
-
SDK .NET 8/9/10 đã cài đặt
-
Studio trực quan hoặc Mã VS
-
Máy chủ Redis chạy cục bộ hoặc qua Docker
Bạn có thể chạy Redis cục bộ bằng Docker:
docker run --name redis -p 6379:6379 -d redis

2. Cài đặt ứng dụng khách Redis
Dự án → Nhấp chuột phải → Quản lý NuGet → Cài đặt:
Microsoft.EntityFrameworkCore
Npgsql.EntityFrameworkCore.PostgreSQL
Microsoft.Extensions.Caching.StackExchangeRedis Bước 3:Thiết lập Program.cs
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// PostgreSQL
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql("Host=localhost;Port=5432;Database=testdb;Username=postgres;Password=1234"));
// Redis
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
});
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run(); Bước 4:Mô hình + DbContext
👉 Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
} 👉 AppDbContext.cs
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}
public DbSet<Product> Products { get; set; }
} Bước 5:Tạo cơ sở dữ liệu (PostgreSQL)
CREATE TABLE "Products" (
"Id" SERIAL PRIMARY KEY,
"Name" TEXT
);
INSERT INTO "Products" ("Name") VALUES ('Laptop'), ('Mobile'); Bước 6:Tạo bộ điều khiển
👉 Thư mục Controllers → Add → Controller → API Controller
👉 ProductController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
private readonly AppDbContext _context;
private readonly IDistributedCache _cache;
public ProductController(AppDbContext context, IDistributedCache cache)
{
_context = context;
_cache = cache;
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
string cacheKey = $"product_{id}";
// 🔴 Redis check
var cachedData = await _cache.GetStringAsync(cacheKey);
if (cachedData != null)
{
var product = JsonSerializer.Deserialize<Product>(cachedData);
return Ok(new
{
source = "Redis",
data = product
});
}
// 🗄️ DB call
var productFromDb = await _context.Products.FindAsync(id);
if (productFromDb == null)
return NotFound();
// 🔥 Save to Redis
var options = new DistributedCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
await _cache.SetStringAsync(
cacheKey,
JsonSerializer.Serialize(productFromDb),
options
);
return Ok(new
{
source = "Database",
data = productFromDb
});
}
} Quy trình làm việc:
-
Trước tiên hãy kiểm tra bộ đệm Redis.
-
Nếu thiếu bộ nhớ cache, hãy tìm nạp từ DB.
-
Lưu trữ dữ liệu trong Redis khi hết hạn.
5. Cách sử dụng Redis nâng cao
-
Băm: Lưu trữ dữ liệu có cấu trúc:
await _db.HashSetAsync("user:1", new HashEntry[]
{
new HashEntry("name", "Shafaet"),
new HashEntry("age", 26)
}); Danh sách: Triển khai hàng đợi hoặc danh sách tin nhắn:
await _db.ListRightPushAsync("messages", "Hello World");
var msg = await _db.ListLeftPopAsync("messages"); Xuất bản/Phụ: Thông báo theo thời gian thực:
var sub = _redis.GetSubscriber();
await sub.SubscribeAsync("channel", (ch, val) => Console.WriteLine(val));
await sub.PublishAsync("channel", "Hello subscribers!");
6. Các phương pháp hay nhất
-
Sử dụng Bộ ghép kênh kết nối dưới dạng một đơn vị để tránh nhiều kết nối.
-
Sử dụng Redis chủ yếu làm bộ đệm , không phải là cơ sở dữ liệu chính.
-
Đặt thời hạn (TTL) cho các khóa được lưu trong bộ nhớ đệm để tránh các vấn đề về bộ nhớ.
🧪 Bước 7:Chạy &Kiểm tra
👉 Chạy dự án
👉 Trình duyệt / Người đưa thư এ gọi:
https://localhost:xxxx/api/product/1
