Computer >> 컴퓨터 >  >> 프로그래밍 >> Redis

.NET 8/9/10과 Redis 통합:포괄적인 단계별 튜토리얼

Redis는 캐싱, 세션 관리, 실시간 분석 등에 널리 사용되는 고성능 인 메모리 데이터 저장소입니다. 이 가이드에서는 StackExchange.Redis를 사용하여 Redis를 .NET 애플리케이션과 통합하는 방법을 살펴보겠습니다. , .NET용으로 가장 인기 있는 Redis 클라이언트 중 하나입니다.

1. 전제 조건

시작하기 전에 다음 사항을 확인하세요.

  • .NET 8/9/10 SDK 설치됨

  • 비주얼 스튜디오 또는 VS 코드

  • Redis 서버 로컬로 또는 Docker를 통해 실행

Docker를 사용하여 Redis를 로컬에서 실행할 수 있습니다:

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

.NET 8/9/10과 Redis 통합:포괄적인 단계별 튜토리얼

2. Redis 클라이언트 설치

프로젝트 → 마우스 오른쪽 버튼 클릭 → NuGet 관리 → 설치:

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단계:모델 + 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단계:데이터베이스 생성(PostgreSQL)

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

6단계:컨트롤러 생성

👉 컨트롤러 폴더 → 추가 → 컨트롤러 → API 컨트롤러

👉 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
 });
 }
}

워크플로:

  1. 먼저 Redis 캐시를 확인하세요.

  2. 캐시가 누락된 경우 DB에서 가져옵니다.

  3. 만료된 데이터를 Redis에 저장합니다.

5. 고급 Redis 사용법

  • 해시: 구조화된 데이터 저장:

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

목록: 대기열 또는 메시지 목록 구현:

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

게시/구독: 실시간 알림:

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

6. 모범 사례

  • ConnectionMultiplexer 사용 여러 연결을 피하기 위해 싱글톤으로 사용하세요.

  • Redis를 주로 캐시로 사용 , 기본 데이터베이스가 아닙니다.

  • 만료일(TTL) 설정 메모리 문제를 방지하기 위해 캐시된 키를 사용하세요.

🧪 7단계:실행 및 테스트

👉 프로젝트 실행
👉 브라우저 / 우편 배달부 এ 전화 :

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

.NET 8/9/10과 Redis 통합:포괄적인 단계별 튜토리얼