Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Redis

การผสานรวม Redis กับ .NET 8/9/10: บทช่วยสอนทีละขั้นตอนฉบับสมบูรณ์

Redis เป็น Data Store ในหน่วยความจำ (In-memory) ที่มีประสิทธิภาพสูง ใช้กันอย่างแพร่หลายสำหรับ Caching, Session Management, Real-time Analytics และอื่นๆ ในคู่มือนี้ เราจะสำรวจวิธีผสานรวม Redis กับแอปพลิเคชัน .NET โดยใช้ StackExchange.Redis หนึ่งใน Redis Client ยอดนิยมที่สุดสำหรับ .NET

1. ข้อกำหนดเบื้องต้น (Prerequisites)

ก่อนเริ่ม ตรวจสอบให้แน่ใจว่าคุณมี:

  • .NET 8/9/10 SDK ติดตั้งแล้ว
  • Visual Studio หรือ VS Code
  • Redis Server รันในเครื่อง (Local) หรือผ่าน Docker

คุณสามารถรัน Redis ในเครื่องด้วย Docker:

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

การผสานรวม Redis กับ .NET 8/9/10: บทช่วยสอนทีละขั้นตอนฉบับสมบูรณ์

2. การติดตั้ง Redis Client

Project → Right click → Manage NuGet → Install:

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

ขั้นตอนที่ 3: การตั้งค่า 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();

ขั้นตอนที่ 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; }
}

ขั้นตอนที่ 5: สร้าง Database (PostgreSQL)

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

ขั้นตอนที่ 6: สร้าง Controller

👉 โฟลเดอร์ 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 Cache
        var cachedData = await _cache.GetStringAsync(cacheKey);
        if (cachedData != null) {
            var product = JsonSerializer.Deserialize<Product>(cachedData);
            return Ok(new { source = "Redis", data = product });
        }
        // 🗄️ เรียก Database
        var productFromDb = await _context.Products.FindAsync(id);
        if (productFromDb == null) return NotFound();
        // 🔥 บันทึกลง 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. ตรวจสอบ Redis Cache ก่อน
  2. ถ้า Cache Miss ให้ดึงจาก DB
  3. เก็บข้อมูลใน Redis พร้อม Expiration

5. การใช้งาน Redis ขั้นสูง (Advanced Redis Usage)

  • Hashes: เก็บข้อมูลที่มีโครงสร้าง:
await _db.HashSetAsync("user:1", new HashEntry[] {
    new HashEntry("name", "Shafaet"),
    new HashEntry("age", 26)
});

Lists: ใช้สำหรับ Queue หรือ Message Lists:

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

Pub/Sub: Real-time Notifications:

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

6. Best Practices

  • ใช้ ConnectionMultiplexer เป็น Singleton เพื่อหลีกเลี่ยงการสร้าง Connection หลายครั้ง
  • ใช้ Redis เป็น Cache หลัก ไม่ใช่ Primary Database
  • ตั้งค่า Expiration (TTL) ให้ Key ที่ Cache ไว้ เพื่อป้องกันปัญหา Memory

🧪 ขั้นตอนที่ 7: Run & Test

👉 Run Project
👉 Browser / Postman เรียก:

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

การผสานรวม Redis กับ .NET 8/9/10: บทช่วยสอนทีละขั้นตอนฉบับสมบูรณ์