Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Tích hợp Redis với .NET 8/9/10: Hướng dẫn từng bước toàn diện

Redis là một data store in-memory hiệu năng cao, dùng rộng rãi cho caching, session management, real-time analytics, và hơn thế nữa. 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 sử dụng StackExchange.Redis, một trong những Redis client phổ biến nhất cho .NET.

1. Điều kiện tiên quyết

Trước khi bắt đầu, đảm bảo bạn có:

  • .NET 8/9/10 SDK đã cài

  • Visual Studio hoặc VS Code

  • Redis server chạy local hoặc qua Docker

Bạn có thể chạy Redis local với Docker:

docker run --name redis -p 6379:6379 -d redis

Tích hợp Redis với .NET 8/9/10: Hướng dẫn từng bước toàn diện

2. Cài đặt Redis Client

Project → Right click → Manage NuGet → Install:

Microsoft.EntityFrameworkCore
Npgsql.EntityFrameworkCore.PostgreSQL
Microsoft.Extensions.Caching.StackExchangeRedis

Bước 3: Cấu hình 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: Model + 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 Database (PostgreSQL)

CREATE TABLE "Products" (
    "Id" SERIAL PRIMARY KEY,
    "Name" TEXT
);
INSERT INTO "Products" ("Name") VALUES ('Laptop'), ('Mobile');

Bước 6: Tạo Controller

👉 Folder 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}";
        // 🔴 Kiểm tra Redis
        var cachedData = await _cache.GetStringAsync(cacheKey);
        if (cachedData != null) {
            var product = JsonSerializer.Deserialize<Product>(cachedData);
            return Ok(new { source = "Redis", data = product });
        }
        // 🗄️ Gọi DB
        var productFromDb = await _context.Products.FindAsync(id);
        if (productFromDb == null) return NotFound();
        // 🔥 Lưu vào Redis
        var options = new DistributedCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
        await _cache.SetStringAsync(
            cacheKey,
            JsonSerializer.Serialize(productFromDb),
            options
        );
        return Ok(new { source = "Database", data = productFromDb });
    }
}

Workflow:

  1. Kiểm tra Redis cache trước.
  2. Nếu cache miss, lấy từ DB.
  3. Lưu dữ liệu vào Redis với expiration.

5. Sử dụng Redis nâng cao

  • Hashes: Lưu dữ liệu có cấu trúc:

await _db.HashSetAsync("user:1", new HashEntry[] {
    new HashEntry("name", "Shafaet"),
    new HashEntry("age", 26)
});

Lists: Triển khai queue hoặc danh sách message:

await _db.ListRightPushAsync("messages", "Hello World");
var msg = await _db.ListLeftPopAsync("messages");

Pub/Sub: Thông báo real-time:

var sub = _redis.GetSubscriber();
await sub.SubscribeAsync("channel", (ch, val) => Console.WriteLine(val));
await sub.PublishAsync("channel", "Hello subscribers!");

6. Best Practices

  • Dùng ConnectionMultiplexer như singleton để tránh multiple connections.
  • Dùng Redis chủ yếu làm cache, không phải primary database.
  • Đặt expiration (TTL) cho cached keys để tránh vấn đề bộ nhớ.

🧪 Bước 7: Run & Test

👉 Chạy project
👉 Browser / Postman gọi:

https://localhost:xxxx/api/product/1

Tích hợp Redis với .NET 8/9/10: Hướng dẫn từng bước toàn diện