Ver3.5 ๐ C# ์บ์ฑ ์ ๋ต ์์ ์ ๋ณต: MemoryCache์ Redis๋ก ์ฑ ์ฑ๋ฅ์ ๋ก์ผ์ฒ๋ผ ๋์ด์ฌ๋ฆฌ๊ธฐ

๐ C# ์บ์ฑ ์ ๋ต ์์ ์ ๋ณต: MemoryCache์ Redis๋ก ์ฑ ์ฑ๋ฅ์ ๋ก์ผ์ฒ๋ผ ๋์ด์ฌ๋ฆฌ๊ธฐ
๋๋ฆฐ ์ฑ์ ์ด์ ๊ทธ๋ง! ์บ์ฑ์ ์ธ๊ณ๋ก ์น๊ตฌ์ฒ๋ผ ํจ๊ป ๋ ๋๋ด์ โจ
์ผ, ์์งํ ๋งํด๋ด. ์ฑ์ด ๋๋ฆด ๋ ์ผ๋ง๋ ์ง์ฆ๋? ๐ค
๋ฒํผ ๋๋ ๋๋ฐ ๋ก๋ฉ ์คํผ๋๊ฐ ๋น๊ธ๋น๊ธ ๋๊ณ ์์ผ๋ฉด... ๊ทธ๋ฅ ์ฐฝ ๋ซ๊ณ ์ถ์์.
๊ทผ๋ฐ ๊ฐ๋ฐ์ ์
์ฅ์์๋ ๋ง์ฐฌ๊ฐ์ง์ผ. DB ์ฟผ๋ฆฌ๊ฐ ๋งค๋ฒ ๋ ์๊ฐ๊ณ , API ํธ์ถ์ด ์์ด๊ณ , ์๋ฒ๋ ํํ๋๊ณ .
์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๋ง๋ฒ ๊ฐ์ ๊ธฐ์ ์ด ๋ฐ๋ก ์บ์ฑ(Caching)์ด์ผ!
์ค๋์ C#์์ ์บ์ฑ์ ์ด๋ป๊ฒ ์ฐ๋์ง, ํนํ MemoryCache์ Redis๋ฅผ ํ์ฉํด์
์ฑ ์ฑ๋ฅ์ ์ง์ง๋ก ๋์ด์ฌ๋ฆฌ๋ ๋ฐฉ๋ฒ์ ์น๊ตฌํํ
์ค๋ช
ํ๋ฏ์ด ์ญ ํ์ด๋ณผ๊ฒ.
์ฝ๋๋ ์๊ณ , ๊ฐ๋
๋ ์๊ณ , ์ค์ ํ๋ ์์ผ๋๊น ๋๊น์ง ๊ฐ์ด ๊ฐ๋ณด์๊ณ ! ๐ช
๐ง ์บ์ฑ์ด ๋ญ์ง ์ ๋๋ก ์๊ณ ๊ฐ์
์บ์ฑ(Caching)์ ๊ฐ๋จํ ๋งํ๋ฉด "์์ฃผ ์ฐ๋ ๋ฐ์ดํฐ๋ฅผ ๋น ๋ฅธ ์ ์ฅ์์ ๋ฏธ๋ฆฌ ์ ์ฅํด๋๋ ๊ฒ"์ด์ผ.
๋ง์น ์์ฃผ ์ฐ๋ ๋ฌผ๊ฑด์ ์๋ ๊น์์ด ๋ฃ์ด๋์ง ์๊ณ ์ฑ
์ ์์ ์ฌ๋ ค๋๋ ๊ฒ์ฒ๋ผ ๋ง์ด์ง. ๐
์๋ฅผ ๋ค์ด๋ณผ๊ฒ. ์ผํ๋ชฐ ์ฑ์์ "๋ฒ ์คํธ์
๋ฌ ์ํ ๋ชฉ๋ก"์ ๋ณด์ฌ์ค๋ค๊ณ ํด๋ด.
์ด ๋ฐ์ดํฐ๊ฐ 1๋ถ๋ง๋ค ๋ฐ๋๋ ๊ฒ ์๋์์? ๊ทธ๋ฐ๋ฐ ์ฌ์ฉ์๊ฐ ํ์ด์ง๋ฅผ ์ด ๋๋ง๋ค
DB์ ์ฟผ๋ฆฌ๋ฅผ ๋ ๋ฆฌ๋ฉด... ๊ทธ๊ฑด ์์ ๋ญ๋น์ผ. ์บ์์ ์ ์ฅํด๋๊ณ ๊บผ๋ด ์ฐ๋ฉด ๋๋ ๊ฑฐ์ง!
Cache Hit : ์์ฒญํ ๋ฐ์ดํฐ๊ฐ ์บ์์ ์์ โ ์ฆ์ ๋ฐํ โก
Cache Miss : ์์ฒญํ ๋ฐ์ดํฐ๊ฐ ์บ์์ ์์ โ DB/API์์ ๊ฐ์ ธ์์ ์บ์์ ์ ์ฅ ํ ๋ฐํ
Cache Eviction : ์บ์ ๊ณต๊ฐ์ด ๋ถ์กฑํ๊ฑฐ๋ ๋ง๋ฃ๋๋ฉด ๋ฐ์ดํฐ๋ฅผ ์ ๊ฑฐํ๋ ๊ฒ
C#์์ ์ธ ์ ์๋ ์บ์ฑ ๋ฐฉ๋ฒ๋ค
C#, ํนํ .NET ํ๊ฒฝ์์๋ ์ฌ๋ฌ ๊ฐ์ง ์บ์ฑ ๋ฐฉ๋ฒ์ ์ ๊ณตํด. ํฌ๊ฒ ์ธ ๊ฐ์ง๋ก ๋๋ ์ ์์ด:
| ์บ์ฑ ๋ฐฉ์ | ํน์ง | ์ ํฉํ ์ํฉ |
|---|---|---|
| IMemoryCache | ์๋ฒ ๋ฉ๋ชจ๋ฆฌ์ ์ ์ฅ, ๋น ๋ฆ | ๋จ์ผ ์๋ฒ, ์๊ท๋ชจ ์ฑ |
| IDistributedCache (Redis) | ์ธ๋ถ ์๋ฒ์ ์ ์ฅ, ๋ถ์ฐ ๊ฐ๋ฅ | ๋ค์ค ์๋ฒ, ๋๊ท๋ชจ ์ฑ |
| Response Caching | HTTP ์๋ต ์์ฒด๋ฅผ ์บ์ฑ | ์ ์ ์ฝํ ์ธ , API ์๋ต |
๐พ IMemoryCache: ์๋ฒ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ด ์ฐฝ๊ณ ๋ก!
๋จผ์ ๊ฐ์ฅ ๊ธฐ๋ณธ์ ์ธ IMemoryCache๋ถํฐ ํํค์ณ๋ณด์.
์ด๊ฑด .NET์ ๋ด์ฅ๋ ์บ์ฑ ์ธํฐํ์ด์ค๋ก, ์๋ฒ์ ๋ฉ๋ชจ๋ฆฌ(RAM)๋ฅผ ์บ์ ์ ์ฅ์๋ก ์ฌ์ฉํด.
์ค์ ๋ ๊ฐ๋จํ๊ณ ์๋๋ ๋น ๋ฅด๋๊น ์
๋ฌธํ๊ธฐ ๋ฑ ์ข์! ๐
๐ฆ ์ค์น ๋ฐ ๋ฑ๋ก
ASP.NET Core์์๋ ๊ธฐ๋ณธ์ผ๋ก ํฌํจ๋์ด ์์ด. Program.cs์ ํ ์ค๋ง ์ถ๊ฐํ๋ฉด ๋ผ:
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// MemoryCache ์๋น์ค ๋ฑ๋ก
builder.Services.AddMemoryCache();
var app = builder.Build();
app.Run();
๐ง ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ
์ด์ ์ปจํธ๋กค๋ฌ๋ ์๋น์ค์์ IMemoryCache๋ฅผ ์ฃผ์
๋ฐ์์ ์จ๋ณด์:
using Microsoft.Extensions.Caching.Memory;
public class ProductService
{
private readonly IMemoryCache _cache;
private readonly IProductRepository _repo;
public ProductService(IMemoryCache cache, IProductRepository repo)
{
_cache = cache;
_repo = repo;
}
public async Task<List<Product>> GetBestSellersAsync()
{
// ์บ์ ํค ์ ์
string cacheKey = "best_sellers";
// ์บ์์์ ๋จผ์ ์ฐพ์๋ณด๊ธฐ
if (_cache.TryGetValue(cacheKey, out List<Product> cachedProducts))
{
Console.WriteLine("โ
์บ์ ํํธ! ๋น ๋ฅด๊ฒ ๋ฐํ");
return cachedProducts;
}
// ์บ์ ๋ฏธ์ค โ DB์์ ๊ฐ์ ธ์ค๊ธฐ
Console.WriteLine("โ ์บ์ ๋ฏธ์ค! DB ์กฐํ ์ค...");
var products = await _repo.GetBestSellersAsync();
// ์บ์ ์ต์
์ค์
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10), // 10๋ถ ํ ๋ง๋ฃ
SlidingExpiration = TimeSpan.FromMinutes(2), // 2๋ถ ๋ฏธ์ฌ์ฉ ์ ๋ง๋ฃ
Priority = CacheItemPriority.Normal
};
// ์บ์์ ์ ์ฅ
_cache.Set(cacheKey, products, cacheOptions);
return products;
}
}
AbsoluteExpiration : "๋ฌด์กฐ๊ฑด ์ด ์๊ฐ ์ดํ์ ๋ง๋ฃ" - ์) 10๋ถ ํ์ ๋ฌด์กฐ๊ฑด ์ญ์
SlidingExpiration : "๋ง์ง๋ง ์ ๊ทผ ํ ์ด ์๊ฐ ๋์ ์ ์ฐ์ด๋ฉด ๋ง๋ฃ" - ์) 2๋ถ๊ฐ ์๋ฌด๋ ์ ์ฐ๋ฉด ์ญ์
๋์ ๊ฐ์ด ์ฐ๋ฉด ๋ ํจ์จ์ ์ด์ผ! Sliding์ด Absolute๋ณด๋ค ๊ธธ์ด์ง๋ ๊ฑด ๋ถ๊ฐ๋ฅํด.
๐ฏ GetOrCreate ํจํด - ๋ ๊น๋ํ๊ฒ!
์ ์ฝ๋๋ฅผ ๋ ๊ฐ๊ฒฐํ๊ฒ ์ธ ์ ์๋ ๋ฐฉ๋ฒ์ด ์์ด. GetOrCreate ๋ฉ์๋๋ฅผ ์จ๋ด:
public async Task<List<Product>> GetBestSellersAsync()
{
return await _cache.GetOrCreateAsync("best_sellers", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
entry.SlidingExpiration = TimeSpan.FromMinutes(2);
// ์บ์ ๋ฏธ์ค์ผ ๋๋ง ์ด ์ฝ๋๊ฐ ์คํ๋จ
return await _repo.GetBestSellersAsync();
});
}
ํจ์ฌ ๊น๋ํ์ง? ๐ GetOrCreateAsync๋ ์บ์์ ์์ผ๋ฉด ์๋์ผ๋ก ํฉํ ๋ฆฌ ํจ์๋ฅผ ์คํํด์ ์ ์ฅ๊น์ง ํด์ค.
์ฝ๋๊ฐ ๋ฐ์ผ๋ก ์ค์์ด!
๐๏ธ ์บ์ ๋ฌดํจํ (Cache Invalidation)
๋ฐ์ดํฐ๊ฐ ๋ณ๊ฒฝ๋์ ๋ ์บ์๋ฅผ ์ง์์ค์ผ ํด. ์ด๊ฑธ ์บ์ ๋ฌดํจํ๋ผ๊ณ ํด:
public async Task UpdateProductAsync(Product product)
{
// DB ์
๋ฐ์ดํธ
await _repo.UpdateAsync(product);
// ๊ด๋ จ ์บ์ ์ญ์
_cache.Remove("best_sellers");
_cache.Remove($"product_{product.Id}");
Console.WriteLine("๐๏ธ ์บ์ ๋ฌดํจํ ์๋ฃ!");
}
๐ท๏ธ CancellationTokenSource๋ก ๊ทธ๋ฃน ์บ์ ์ญ์
๊ด๋ จ๋ ์บ์๋ฅผ ํ ๋ฒ์ ์ง์ฐ๊ณ ์ถ์ ๋๋ CancellationTokenSource๋ฅผ ํ์ฉํด:
public class ProductCacheService
{
private readonly IMemoryCache _cache;
private CancellationTokenSource _resetToken = new();
// ์บ์ ์ ์ฅ ์ ํ ํฐ ์ฐ๊ฒฐ
public void SetWithGroupToken(string key, object value)
{
var options = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(10))
.AddExpirationToken(new CancellationChangeToken(_resetToken.Token));
_cache.Set(key, value, options);
}
// ๊ทธ๋ฃน ์ ์ฒด ์บ์ ๋ฌดํจํ
public void InvalidateAll()
{
_resetToken.Cancel();
_resetToken.Dispose();
_resetToken = new CancellationTokenSource(); // ์ ํ ํฐ ์์ฑ
Console.WriteLine("๐ฅ ์ ์ฒด ์บ์ ๊ทธ๋ฃน ๋ฌดํจํ!");
}
}
๐ด Redis: ๋ถ์ฐ ์บ์ฑ์ ์์ข์ ์ค๋ฅด๋ค
์, ์ด์ ์ง์ง ๊ฐ๋ ฅํ ๋
์์ ๋ง๋๋ณผ ์๊ฐ์ด์ผ. Redis(Remote Dictionary Server)!
Redis๋ ์คํ์์ค ์ธ๋ฉ๋ชจ๋ฆฌ ๋ฐ์ดํฐ ๊ตฌ์กฐ ์ ์ฅ์๋ก, ์บ์ฑ ์ฉ๋๋ก ์ ์ธ๊ณ์์ ๊ฐ์ฅ ๋ง์ด ์ฐ์ด๋ ์๋ฃจ์
์ด์ผ.
Twitter, GitHub, Stack Overflow ๊ฐ์ ๋ํ ์๋น์ค๋ค๋ Redis๋ฅผ ์ฐ๊ณ ์์ด. ๐ฎ
C#์์ Redis๋ฅผ ์ฐ๋ ๋ฐฉ๋ฒ์ ํฌ๊ฒ ๋ ๊ฐ์ง์ผ:
1. IDistributedCache (Microsoft ๊ณต์ ์ถ์ํ) 2. StackExchange.Redis (์ง์ Redis ํด๋ผ์ด์ธํธ)
๐ฆ ํจํค์ง ์ค์น
# NuGet ํจํค์ง ์ค์น
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
dotnet add package StackExchange.Redis
โ๏ธ Redis ์ฐ๊ฒฐ ์ค์
// appsettings.json
{
"ConnectionStrings": {
"Redis": "localhost:6379,abortConnect=false,connectTimeout=5000"
}
}
// Program.cs
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("Redis");
options.InstanceName = "MyApp_"; // ํค ์์ ๋ถ๋ ์ ๋์ฌ
});
๐ฎ IDistributedCache ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ
IDistributedCache๋ ๋ฐ์ดํธ ๋ฐฐ์ด๋ก ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํด. ๊ทธ๋์ ์ง๋ ฌํ/์ญ์ง๋ ฌํ๊ฐ ํ์ํด:
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
public class UserService
{
private readonly IDistributedCache _cache;
private readonly IUserRepository _repo;
public UserService(IDistributedCache cache, IUserRepository repo)
{
_cache = cache;
_repo = repo;
}
public async Task<User?> GetUserAsync(int userId)
{
string cacheKey = $"user_{userId}";
// ์บ์์์ ๊ฐ์ ธ์ค๊ธฐ
byte[]? cachedData = await _cache.GetAsync(cacheKey);
if (cachedData != null)
{
// ์ญ์ง๋ ฌํ
return JsonSerializer.Deserialize<User>(cachedData);
}
// DB์์ ๊ฐ์ ธ์ค๊ธฐ
var user = await _repo.GetByIdAsync(userId);
if (user == null) return null;
// ์ง๋ ฌํ ํ ์บ์ ์ ์ฅ
byte[] serializedData = JsonSerializer.SerializeToUtf8Bytes(user);
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1),
SlidingExpiration = TimeSpan.FromMinutes(20)
};
await _cache.SetAsync(cacheKey, serializedData, options);
return user;
}
public async Task RemoveUserCacheAsync(int userId)
{
await _cache.RemoveAsync($"user_{userId}");
}
}
System.Text.Json์ ๋น ๋ฅด๊ณ ๊ฐ๋ณ์ง๋ง, ๋ณต์กํ ๊ฐ์ฒด๋ ๋์ฉ๋ ๋ฐ์ดํฐ์๋MessagePack์ด๋ Protobuf ๊ฐ์ ๋ฐ์ด๋๋ฆฌ ์ง๋ ฌํ๋ฅผ ๊ณ ๋ คํด๋ด.
JSON ๋๋น 2~5๋ฐฐ ๋น ๋ฅด๊ณ ํฌ๊ธฐ๋ ํจ์ฌ ์์!
๐ StackExchange.Redis ์ง์ ์ฌ์ฉ - ๋ ๊ฐ๋ ฅํ๊ฒ!
IDistributedCache๋ ํธ๋ฆฌํ์ง๋ง Redis์ ๊ณ ๊ธ ๊ธฐ๋ฅ์ ๋ค ์ฐ์ง ๋ชปํด.
StackExchange.Redis๋ฅผ ์ง์ ์ฐ๋ฉด Redis์ ๋ชจ๋ ๊ธฐ๋ฅ์ ํ์ฉํ ์ ์์ด:
// Program.cs - ConnectionMultiplexer ์ฑ๊ธํค ๋ฑ๋ก
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
var config = ConfigurationOptions.Parse("localhost:6379");
config.AbortOnConnectFail = false;
config.ConnectTimeout = 5000;
config.SyncTimeout = 5000;
return ConnectionMultiplexer.Connect(config);
});
// RedisService.cs
using StackExchange.Redis;
using System.Text.Json;
public class RedisService
{
private readonly IDatabase _db;
public RedisService(IConnectionMultiplexer redis)
{
_db = redis.GetDatabase();
}
// ๋ฌธ์์ด ์ ์ฅ/์กฐํ
public async Task SetStringAsync(string key, string value, TimeSpan? expiry = null)
{
await _db.StringSetAsync(key, value, expiry);
}
public async Task<string?> GetStringAsync(string key)
{
RedisValue value = await _db.StringGetAsync(key);
return value.IsNullOrEmpty ? null : value.ToString();
}
// ๊ฐ์ฒด ์ ์ฅ/์กฐํ (JSON ์ง๋ ฌํ)
public async Task SetObjectAsync<T>(string key, T obj, TimeSpan? expiry = null)
{
string json = JsonSerializer.Serialize(obj);
await _db.StringSetAsync(key, json, expiry);
}
public async Task<T?> GetObjectAsync<T>(string key)
{
RedisValue value = await _db.StringGetAsync(key);
if (value.IsNullOrEmpty) return default;
return JsonSerializer.Deserialize<T>(value.ToString());
}
// ์นด์ดํฐ (์์์ ์ฆ๊ฐ)
public async Task<long> IncrementAsync(string key)
{
return await _db.StringIncrementAsync(key);
}
// ํด์ ์ ์ฅ (๊ฐ์ฒด ํ๋๋ณ ์ ์ฅ)
public async Task SetHashAsync(string key, string field, string value)
{
await _db.HashSetAsync(key, field, value);
}
// ํค ์กด์ฌ ์ฌ๋ถ ํ์ธ
public async Task<bool> ExistsAsync(string key)
{
return await _db.KeyExistsAsync(key);
}
// TTL ์ค์
public async Task SetExpiryAsync(string key, TimeSpan expiry)
{
await _db.KeyExpireAsync(key, expiry);
}
}
๐๏ธ ์ค์ ์บ์ฑ ์ ๋ต ํจํด๋ค
์บ์ฑ์ ์ฐ๋ ๋ฐฉ๋ฒ์ ์ฌ๋ฌ ๊ฐ์ง์ผ. ์ํฉ์ ๋ง๋ ์ ๋ต์ ์ ํํ๋ ๊ฒ ์ค์ํด!
๋ง์น ์๋ฆฌํ ๋ ์ฌ๋ฃ์ ๋ฐ๋ผ ์กฐ๋ฆฌ๋ฒ์ ๋ค๋ฅด๊ฒ ํ๋ ๊ฒ์ฒ๋ผ ๋ง์ด์ง. ๐ณ
1๏ธโฃ Cache-Aside ํจํด (๊ฐ์ฅ ์ผ๋ฐ์ )
์ฑ์ด ์ง์ ์บ์๋ฅผ ๊ด๋ฆฌํ๋ ๋ฐฉ์. ์์์ ๋ณธ ์์ ๋ค์ด ๋ค ์ด ํจํด์ด์ผ.
// Cache-Aside ํจํด
public async Task<Product> GetProductAsync(int id)
{
string key = $"product:{id}";
// 1. ์บ์ ํ์ธ
var cached = await _cache.GetObjectAsync<Product>(key);
if (cached != null) return cached; // Cache Hit!
// 2. ์๋ณธ ๋ฐ์ดํฐ ์กฐํ
var product = await _db.Products.FindAsync(id);
// 3. ์บ์์ ์ ์ฅ
if (product != null)
await _cache.SetObjectAsync(key, product, TimeSpan.FromMinutes(30));
return product;
}
2๏ธโฃ Write-Through ํจํด
๋ฐ์ดํฐ๋ฅผ ์ธ ๋ DB์ ์บ์๋ฅผ ๋์์ ์ ๋ฐ์ดํธ. ์บ์์ DB์ ์ผ๊ด์ฑ์ด ํญ์ ์ ์ง๋ผ:
// Write-Through ํจํด
public async Task UpdateProductAsync(Product product)
{
// 1. DB ์
๋ฐ์ดํธ
_dbContext.Products.Update(product);
await _dbContext.SaveChangesAsync();
// 2. ์บ์๋ ๋์์ ์
๋ฐ์ดํธ (์ญ์ ๊ฐ ์๋ ๊ฐฑ์ !)
string key = $"product:{product.Id}";
await _cache.SetObjectAsync(key, product, TimeSpan.FromMinutes(30));
Console.WriteLine("โ
DB์ ์บ์ ๋์ ์
๋ฐ์ดํธ ์๋ฃ!");
}
3๏ธโฃ Write-Behind (Write-Back) ํจํด
์บ์์ ๋จผ์ ์ฐ๊ณ , ๋์ค์ ๋น๋๊ธฐ๋ก DB์ ๋ฐ์. ์ฐ๊ธฐ ์ฑ๋ฅ์ด ๊ทน๋ํ๋์ง๋ง ๋ฐ์ดํฐ ์์ค ์ํ์ด ์์ด:
// Write-Behind ํจํด (๊ฐ๋จํ ์์)
public async Task UpdateViewCountAsync(int productId)
{
string key = $"viewcount:{productId}";
// ์บ์์ ์ฆ์ ๋ฐ์ (์์์ ์ฆ๊ฐ)
long newCount = await _redis.IncrementAsync(key);
// ์ผ์ ์ฃผ๊ธฐ๋ก DB์ ๋ฐ์ (๋ฐฑ๊ทธ๋ผ์ด๋ ์์
)
// ์: 100๋ฒ ์ฆ๊ฐํ ๋๋ง๋ค ๋๋ 5๋ถ๋ง๋ค DB ๋๊ธฐํ
if (newCount % 100 == 0)
{
_ = Task.Run(async () =>
{
await _repo.UpdateViewCountAsync(productId, newCount);
});
}
}
4๏ธโฃ Read-Through ํจํด
์บ์ ๋ ์ด์ด๊ฐ ์๋์ผ๋ก DB์์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ ์บ์์ ์ฑ์์ฃผ๋ ๋ฐฉ์.
์ฑ ์ฝ๋๊ฐ ์บ์๋ง ๋ฐ๋ผ๋ณด๋ฉด ๋ผ:
// Read-Through๋ฅผ ๊ตฌํํ๋ ์ ๋ค๋ฆญ ์บ์ ์๋น์ค
public class CacheService<T>
{
private readonly IDistributedCache _cache;
public async Task<T?> GetOrLoadAsync(
string key,
Func<Task<T?>> loader,
TimeSpan expiry)
{
// ์บ์ ํ์ธ
var cached = await GetFromCacheAsync<T>(key);
if (cached != null) return cached;
// ๋ก๋ ํจ์๋ก ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ (DB, API ๋ฑ)
var data = await loader();
if (data != null)
await SetToCacheAsync(key, data, expiry);
return data;
}
private async Task<T?> GetFromCacheAsync<T>(string key)
{
var bytes = await _cache.GetAsync(key);
if (bytes == null) return default;
return JsonSerializer.Deserialize<T>(bytes);
}
private async Task SetToCacheAsync<T>(string key, T data, TimeSpan expiry)
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(data);
await _cache.SetAsync(key, bytes, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = expiry
});
}
}
// ์ฌ์ฉ ์์
var product = await _cacheService.GetOrLoadAsync(
$"product:{id}",
() => _repo.GetByIdAsync(id),
TimeSpan.FromMinutes(30)
);
โก ๊ณ ๊ธ Redis ๊ธฐ๋ฅ ํ์ฉํ๊ธฐ
Redis๋ ๋จ์ํ ํค-๊ฐ ์ ์ฅ์๊ฐ ์๋์ผ. ๋ค์ํ ๋ฐ์ดํฐ ๊ตฌ์กฐ๋ฅผ ์ง์ํด์
์บ์ฑ ์ด์์ ํ์ฉ์ด ๊ฐ๋ฅํด. ๋ช ๊ฐ์ง ์ค์ ์์ ๋ฅผ ๋ณด์ฌ์ค๊ฒ! ๐ฏ
๐ข Redis Hash - ๊ฐ์ฒด ํ๋๋ณ ๊ด๋ฆฌ
์ฌ์ฉ์ ์ธ์ ์ด๋ ์ค์ ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ํ๋๋ณ๋ก ๊ด๋ฆฌํ ๋ ์ ์ฉํด:
// Redis Hash ํ์ฉ
public class UserSessionService
{
private readonly IDatabase _db;
public async Task SetUserSessionAsync(string userId, UserSession session)
{
string key = $"session:{userId}";
// ํ๋๋ณ๋ก ์ ์ฅ
await _db.HashSetAsync(key, new HashEntry[]
{
new HashEntry("name", session.Name),
new HashEntry("email", session.Email),
new HashEntry("role", session.Role),
new HashEntry("loginTime", session.LoginTime.ToString("O"))
});
// TTL ์ค์ (1์๊ฐ)
await _db.KeyExpireAsync(key, TimeSpan.FromHours(1));
}
public async Task<string?> GetUserRoleAsync(string userId)
{
// ์ ์ฒด ๊ฐ์ฒด๊ฐ ์๋ ํน์ ํ๋๋ง ๊ฐ์ ธ์ค๊ธฐ (ํจ์จ์ !)
RedisValue role = await _db.HashGetAsync($"session:{userId}", "role");
return role.IsNullOrEmpty ? null : role.ToString();
}
public async Task UpdateUserNameAsync(string userId, string newName)
{
// ํน์ ํ๋๋ง ์
๋ฐ์ดํธ (์ ์ฒด ๊ฐ์ฒด ์ฌ์ ์ฅ ๋ถํ์!)
await _db.HashSetAsync($"session:{userId}", "name", newName);
}
}
๐ Redis List - ์ต๊ทผ ํญ๋ชฉ ๊ด๋ฆฌ
์ต๊ทผ ๋ณธ ์ํ, ์๋ฆผ ๋ชฉ๋ก ๊ฐ์ ์์๊ฐ ์๋ ๋ฐ์ดํฐ์ ๋ฑ์ด์ผ:
// Redis List๋ก ์ต๊ทผ ๋ณธ ์ํ ๊ด๋ฆฌ
public class RecentlyViewedService
{
private readonly IDatabase _db;
private const int MaxItems = 10; // ์ต๋ 10๊ฐ ์ ์ง
public async Task AddViewedProductAsync(string userId, int productId)
{
string key = $"recent:{userId}";
// ์ผ์ชฝ์ ์ถ๊ฐ (์ต์ ์ด ์์)
await _db.ListLeftPushAsync(key, productId.ToString());
// ์ค๋ณต ์ ๊ฑฐ (๊ฐ์ ์ํ์ด ์ฌ๋ฌ ๋ฒ ๋ค์ด๊ฐ์ง ์๋๋ก)
// ์ค์ ๋ก๋ Lua ์คํฌ๋ฆฝํธ๋ก ์์์ ์ผ๋ก ์ฒ๋ฆฌํ๋ ๊ฒ ์ข์
// ์ต๋ ๊ฐ์ ์ ์ง (์ค๋๋ ๊ฒ ์๋ ์ ๊ฑฐ)
await _db.ListTrimAsync(key, 0, MaxItems - 1);
// TTL ๊ฐฑ์
await _db.KeyExpireAsync(key, TimeSpan.FromDays(7));
}
public async Task<List<int>> GetRecentProductsAsync(string userId)
{
string key = $"recent:{userId}";
RedisValue[] values = await _db.ListRangeAsync(key, 0, -1);
return values.Select(v => int.Parse(v.ToString())).ToList();
}
}
๐ Redis Sorted Set - ๋ญํน ์์คํ
์ ์ ๊ธฐ๋ฐ ๋ญํน์ด ํ์ํ ๋ Redis Sorted Set์ ์ต๊ณ ์ ์ ํ์ด์ผ:
// Redis Sorted Set์ผ๋ก ์ค์๊ฐ ๋ญํน
public class LeaderboardService
{
private readonly IDatabase _db;
private const string LeaderboardKey = "leaderboard:global";
public async Task AddScoreAsync(string userId, double score)
{
// ์ ์ ์ถ๊ฐ (๊ธฐ์กด ์ ์์ ๋ํ๊ธฐ)
await _db.SortedSetIncrementAsync(LeaderboardKey, userId, score);
}
public async Task<long?> GetRankAsync(string userId)
{
// ์์ ์กฐํ (0๋ถํฐ ์์, ๋์ ์ ์๊ฐ ๋ฎ์ ์ธ๋ฑ์ค)
return await _db.SortedSetRankAsync(LeaderboardKey, userId, Order.Descending);
}
public async Task<List<(string UserId, double Score)>> GetTopPlayersAsync(int count)
{
// ์์ N๋ช
์กฐํ
SortedSetEntry[] entries = await _db.SortedSetRangeByRankWithScoresAsync(
LeaderboardKey, 0, count - 1, Order.Descending);
return entries.Select(e => (e.Element.ToString(), e.Score)).ToList();
}
}
๐ Redis ๋ถ์ฐ ๋ฝ (Distributed Lock)
์ฌ๋ฌ ์๋ฒ์์ ๋์์ ๊ฐ์ ์์
์ด ์คํ๋๋ ๊ฑธ ๋ง์ ๋ ์ฌ์ฉํด:
์๋ฅผ ๋ค์ด "์ฌ๊ณ ์ฐจ๊ฐ"์ด๋ "์ฟ ํฐ ๋ฐ๊ธ" ๊ฐ์ ์ค์ํ ์์
์ ํ์์ผ!
// Redis ๋ถ์ฐ ๋ฝ ๊ตฌํ
public class RedisLockService
{
private readonly IDatabase _db;
public async Task<bool> AcquireLockAsync(string resource, string lockId, TimeSpan expiry)
{
string lockKey = $"lock:{resource}";
// NX (Not eXists) ์ต์
: ํค๊ฐ ์์ ๋๋ง ์ค์ (์์์ ์ฐ์ฐ)
bool acquired = await _db.StringSetAsync(
lockKey,
lockId,
expiry,
When.NotExists
);
return acquired;
}
public async Task ReleaseLockAsync(string resource, string lockId)
{
string lockKey = $"lock:{resource}";
// Lua ์คํฌ๋ฆฝํธ๋ก ์์์ ํ์ธ ํ ์ญ์ (๋ด๊ฐ ๊ฑด ๋ฝ๋ง ํด์ )
string script = @"
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
else
return 0
end";
await _db.ScriptEvaluateAsync(script,
new RedisKey[] { lockKey },
new RedisValue[] { lockId });
}
}
// ์ฌ์ฉ ์์
public async Task ProcessOrderAsync(int orderId)
{
string lockId = Guid.NewGuid().ToString();
string resource = $"order:{orderId}";
bool locked = await _lockService.AcquireLockAsync(resource, lockId, TimeSpan.FromSeconds(30));
if (!locked)
{
throw new InvalidOperationException("๋ค๋ฅธ ํ๋ก์ธ์ค๊ฐ ์ฒ๋ฆฌ ์ค์
๋๋ค.");
}
try
{
// ์ค์ํ ์์
์ํ
await ProcessOrderInternalAsync(orderId);
}
finally
{
await _lockService.ReleaseLockAsync(resource, lockId);
}
}
๐ก๏ธ ์บ์ฑ ํจ์ ๊ณผ ํด๊ฒฐ์ฑ : ์ด๊ฒ๋ง์ ๊ผญ ์์๋์!
์บ์ฑ์ด ๋ง๋ฅ์ ์๋์ผ. ์๋ชป ์ฐ๋ฉด ์คํ๋ ค ๋ ํฐ ๋ฌธ์ ๊ฐ ์๊ธธ ์ ์์ด.
๊ฐ๋ฐ์๋ค์ด ์์ฃผ ๋น ์ง๋ ํจ์ ๋ค์ ๋ฏธ๋ฆฌ ์์๋์! โ ๏ธ
๐ฅ 1. Cache Stampede (์บ์ ์คํฌํผ๋)
์บ์๊ฐ ๋ง๋ฃ๋๋ ์๊ฐ, ์๋ฐฑ ๊ฐ์ ์์ฒญ์ด ๋์์ DB๋ก ๋ชฐ๋ฆฌ๋ ํ์์ด์ผ.
๋ง์น ์ฝ์ํธ ํฐ์ผ ์คํ ์๊ฐ์ฒ๋ผ... ์๋ฒ๊ฐ ํฐ์ง ์ ์์ด! ๐ฑ
// ๋ฌธ์ : ๋์์ ์บ์ ๋ฏธ์ค๊ฐ ๋ฐ์ํ๋ฉด ๋ชจ๋ DB ์กฐํ
// ํด๊ฒฐ: ๋ฎคํ
์ค(Mutex) ๋๋ SemaphoreSlim์ผ๋ก ๋์ ์ ๊ทผ ์ ํ
public class StampedeProtectedCache
{
private readonly IMemoryCache _cache;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
public async Task<T?> GetOrCreateSafeAsync<T>(
string key,
Func<Task<T?>> factory,
TimeSpan expiry)
{
// ๋จผ์ ์บ์ ํ์ธ (๋ฝ ์์ด)
if (_cache.TryGetValue(key, out T? cached))
return cached;
// ์บ์ ๋ฏธ์ค ์ ๋ฝ ํ๋
await _semaphore.WaitAsync();
try
{
// ๋ฝ ํ๋ ํ ๋ค์ ํ์ธ (๋ค๋ฅธ ์ค๋ ๋๊ฐ ์ด๋ฏธ ์ฑ์ ์ ์ ์์)
if (_cache.TryGetValue(key, out cached))
return cached;
// ์ค์ ๋ฐ์ดํฐ ๋ก๋
var data = await factory();
if (data != null)
{
_cache.Set(key, data, expiry);
}
return data;
}
finally
{
_semaphore.Release();
}
}
}
๐ณ๏ธ 2. Cache Penetration (์บ์ ์นจํฌ)
์กด์ฌํ์ง ์๋ ๋ฐ์ดํฐ๋ฅผ ๊ณ์ ์์ฒญํ๋ฉด, ์บ์์ ์์ผ๋ ๋งค๋ฒ DB๋ฅผ ์กฐํํ๊ฒ ๋ผ.
์
์์ ์ธ ๊ณต๊ฒฉ์๋ ์ทจ์ฝํด์ง ์ ์์ด:
// ํด๊ฒฐ: Null ๊ฐ๋ ์บ์ฑํ๊ธฐ (Null Object Pattern)
public async Task<Product?> GetProductSafeAsync(int id)
{
string key = $"product:{id}";
// ํน๋ณํ "์์" ๋ง์ปค ๊ฐ ์ฌ์ฉ
const string NULL_MARKER = "__NULL__";
var cached = await _redis.GetStringAsync(key);
if (cached == NULL_MARKER)
{
// ์๋ ๋ฐ์ดํฐ์์ ์บ์๊ฐ ์๋ ค์ค โ DB ์กฐํ ์ ํจ
return null;
}
if (cached != null)
{
return JsonSerializer.Deserialize<Product>(cached);
}
// DB ์กฐํ
var product = await _repo.GetByIdAsync(id);
if (product == null)
{
// ์๋ ๋ฐ์ดํฐ๋ ์งง์ ์๊ฐ ์บ์ฑ (5๋ถ)
await _redis.SetStringAsync(key, NULL_MARKER, TimeSpan.FromMinutes(5));
return null;
}
await _redis.SetObjectAsync(key, product, TimeSpan.FromMinutes(30));
return product;
}
๐ 3. Cache Avalanche (์บ์ ๋์ฌํ)
๋ง์ ์บ์ ํญ๋ชฉ์ด ๋์์ ๋ง๋ฃ๋๋ฉด DB์ ๊ฐ์๊ธฐ ์์ฒญ๋ ๋ถํ๊ฐ ๊ฑธ๋ ค.
ํด๊ฒฐ์ฑ
์ ๋ง๋ฃ ์๊ฐ์ ๋๋ค ์งํฐ(Jitter)๋ฅผ ์ถ๊ฐํ๋ ๊ฑฐ์ผ:
// ๋ง๋ฃ ์๊ฐ์ ๋๋ค ์งํฐ ์ถ๊ฐ
public TimeSpan GetJitteredExpiry(TimeSpan baseExpiry, double jitterPercent = 0.1)
{
var random = new Random();
double jitter = baseExpiry.TotalSeconds * jitterPercent;
double randomJitter = (random.NextDouble() * 2 - 1) * jitter; // -jitter ~ +jitter
return TimeSpan.FromSeconds(baseExpiry.TotalSeconds + randomJitter);
}
// ์ฌ์ฉ ์์
var expiry = GetJitteredExpiry(TimeSpan.FromMinutes(30)); // 27~33๋ถ ์ฌ์ด ๋๋ค
await _cache.SetObjectAsync(key, data, expiry);
- โ ์์ฃผ ๋ณํ๋ ๋ฐ์ดํฐ๋ฅผ ๊ธด TTL๋ก ์บ์ฑ โ ์ค๋๋ ๋ฐ์ดํฐ ์ ๊ณต
- โ ๋๋ฌด ๋ง์ ๋ฐ์ดํฐ๋ฅผ ์บ์ฑ โ ๋ฉ๋ชจ๋ฆฌ ๋ถ์กฑ, OOM ๋ฐ์
- โ ์บ์ ํค ์ถฉ๋ โ ๋ค๋ฅธ ๋ฐ์ดํฐ๊ฐ ๋ฎ์ด์์์ง
- โ ๋ฏผ๊ฐํ ๋ฐ์ดํฐ(๋น๋ฐ๋ฒํธ, ๊ฒฐ์ ์ ๋ณด) ์บ์ฑ โ ๋ณด์ ์ํ
- โ ์บ์ ์์กด์ฑ ๊ณผ๋ค โ Redis ์ฅ์ ์ ์ ์ฒด ์๋น์ค ๋ค์ด
๐ ์ฑ๋ฅ ๋ชจ๋ํฐ๋ง: ์บ์๊ฐ ์ ์๋ํ๋์ง ํ์ธํ์
์บ์ฑ์ ์ ์ฉํ๋ค๊ณ ๋์ด ์๋์ผ! ์ ๋๋ก ์๋ํ๋์ง ๋ชจ๋ํฐ๋งํด์ผ ํด.
์บ์ ํํธ์จ(Cache Hit Rate)์ด ํต์ฌ ์งํ์ผ. ๋ณดํต 80% ์ด์์ด๋ฉด ์ข์ ๊ฑฐ์ผ. ๐
๐ MemoryCache ํต๊ณ ์์ง
// MemoryCache ํต๊ณ ์์ง ์๋น์ค
public class CacheMetricsService
{
private long _hitCount = 0;
private long _missCount = 0;
private readonly IMemoryCache _cache;
public async Task<T?> GetWithMetricsAsync<T>(string key, Func<Task<T?>> factory, TimeSpan expiry)
{
if (_cache.TryGetValue(key, out T? value))
{
Interlocked.Increment(ref _hitCount); // ์ค๋ ๋ ์์ ์ฆ๊ฐ
return value;
}
Interlocked.Increment(ref _missCount);
var data = await factory();
if (data != null) _cache.Set(key, data, expiry);
return data;
}
public double GetHitRate()
{
long total = _hitCount + _missCount;
if (total == 0) return 0;
return (double)_hitCount / total * 100;
}
public void PrintStats()
{
Console.WriteLine($"๐ ์บ์ ํต๊ณ:");
Console.WriteLine($" ํํธ: {_hitCount}ํ");
Console.WriteLine($" ๋ฏธ์ค: {_missCount}ํ");
Console.WriteLine($" ํํธ์จ: {GetHitRate():F1}%");
}
}
๐ Redis ๋ชจ๋ํฐ๋ง ๋ช ๋ น์ด
# Redis CLI์์ ์ค์๊ฐ ํต๊ณ ํ์ธ
redis-cli INFO stats
# ์ฃผ์ ์งํ
# keyspace_hits: ์บ์ ํํธ ํ์
# keyspace_misses: ์บ์ ๋ฏธ์ค ํ์
# used_memory_human: ์ฌ์ฉ ์ค์ธ ๋ฉ๋ชจ๋ฆฌ
# connected_clients: ์ฐ๊ฒฐ๋ ํด๋ผ์ด์ธํธ ์
# ํํธ์จ ๊ณ์ฐ
# hit_rate = keyspace_hits / (keyspace_hits + keyspace_misses) * 100
# ์ค์๊ฐ ๋ช
๋ น์ด ๋ชจ๋ํฐ๋ง (๊ฐ๋ฐ ํ๊ฒฝ์์๋ง!)
redis-cli MONITOR
๐ฅ Redis ์ฐ๊ฒฐ ๋ณต์๋ ฅ (Resilience)
Redis๊ฐ ๋ค์ด๋์ ๋ ์ฑ ์ ์ฒด๊ฐ ์ฃฝ์ผ๋ฉด ์ ๋์์? ํด๋ฐฑ(Fallback) ์ฒ๋ฆฌ๋ฅผ ํด์ค์ผ ํด:
// Redis ์ฅ์ ์ ํด๋ฐฑ ์ฒ๋ฆฌ
public class ResilientCacheService
{
private readonly IDistributedCache _redis;
private readonly IMemoryCache _fallbackCache;
private readonly ILogger<ResilientCacheService> _logger;
public async Task<T?> GetAsync<T>(string key)
{
try
{
// Redis ์๋
var bytes = await _redis.GetAsync(key);
if (bytes != null)
return JsonSerializer.Deserialize<T>(bytes);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Redis ์กฐํ ์คํจ, ๋ก์ปฌ ์บ์๋ก ํด๋ฐฑ");
// Redis ์คํจ ์ ๋ก์ปฌ ๋ฉ๋ชจ๋ฆฌ ์บ์๋ก ํด๋ฐฑ
if (_fallbackCache.TryGetValue(key, out T? fallback))
return fallback;
}
return default;
}
public async Task SetAsync<T>(string key, T value, TimeSpan expiry)
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(value);
try
{
await _redis.SetAsync(key, bytes, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = expiry
});
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Redis ์ ์ฅ ์คํจ, ๋ก์ปฌ ์บ์์๋ง ์ ์ฅ");
}
// ํญ์ ๋ก์ปฌ ์บ์์๋ ์ ์ฅ (ํด๋ฐฑ์ฉ)
_fallbackCache.Set(key, value, expiry);
}
}
๐จ ์ค์ ์์ : ์์ฑ๋ ์บ์ฑ ๋ ์ด์ด ๋ง๋ค๊ธฐ
์ง๊ธ๊น์ง ๋ฐฐ์ด ๊ฑธ ์ข
ํฉํด์ ์ค์ ํ๋ก์ ํธ์ ๋ฐ๋ก ์ธ ์ ์๋
์์ฑ๋ ์บ์ฑ ์๋น์ค๋ฅผ ๋ง๋ค์ด๋ณผ๊ฒ. ์ฌ๋ฅ๋ท ๊ฐ์ ํ๋ซํผ์์๋ ์ด๋ฐ ๊ตฌ์กฐ๋ฅผ ์ธ ์ ์์ด! ๐๏ธ
// ICacheService.cs - ์ธํฐํ์ด์ค ์ ์
public interface ICacheService
{
Task<T?> GetAsync<T>(string key);
Task SetAsync<T>(string key, T value, TimeSpan? expiry = null);
Task RemoveAsync(string key);
Task<T?> GetOrSetAsync<T>(string key, Func<Task<T?>> factory, TimeSpan? expiry = null);
Task RemoveByPatternAsync(string pattern);
}
// CacheService.cs - ๊ตฌํ์ฒด
public class CacheService : ICacheService
{
private readonly IDistributedCache _cache;
private readonly IConnectionMultiplexer _redis;
private readonly ILogger<CacheService> _logger;
private readonly TimeSpan _defaultExpiry = TimeSpan.FromMinutes(30);
public CacheService(
IDistributedCache cache,
IConnectionMultiplexer redis,
ILogger<CacheService> logger)
{
_cache = cache;
_redis = redis;
_logger = logger;
}
public async Task<T?> GetAsync<T>(string key)
{
try
{
var bytes = await _cache.GetAsync(key);
if (bytes == null) return default;
return JsonSerializer.Deserialize<T>(bytes);
}
catch (Exception ex)
{
_logger.LogError(ex, "์บ์ ์กฐํ ์คํจ: {Key}", key);
return default;
}
}
public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null)
{
try
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(value);
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = expiry ?? _defaultExpiry
};
await _cache.SetAsync(key, bytes, options);
}
catch (Exception ex)
{
_logger.LogError(ex, "์บ์ ์ ์ฅ ์คํจ: {Key}", key);
}
}
public async Task RemoveAsync(string key)
{
try
{
await _cache.RemoveAsync(key);
}
catch (Exception ex)
{
_logger.LogError(ex, "์บ์ ์ญ์ ์คํจ: {Key}", key);
}
}
public async Task<T?> GetOrSetAsync<T>(
string key,
Func<Task<T?>> factory,
TimeSpan? expiry = null)
{
var cached = await GetAsync<T>(key);
if (cached != null) return cached;
var data = await factory();
if (data != null)
await SetAsync(key, data, expiry);
return data;
}
// ํจํด์ผ๋ก ์ฌ๋ฌ ํค ์ญ์ (Redis ์ ์ฉ)
public async Task RemoveByPatternAsync(string pattern)
{
try
{
var server = _redis.GetServer(_redis.GetEndPoints().First());
var keys = server.Keys(pattern: $"*{pattern}*").ToArray();
if (keys.Any())
{
var db = _redis.GetDatabase();
await db.KeyDeleteAsync(keys);
_logger.LogInformation("{Count}๊ฐ ์บ์ ํค ์ญ์ : {Pattern}", keys.Length, pattern);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "ํจํด ์บ์ ์ญ์ ์คํจ: {Pattern}", pattern);
}
}
}
// Program.cs์ ๋ฑ๋ก
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")!));
builder.Services.AddStackExchangeRedisCache(options =>
options.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddScoped<ICacheService, CacheService>();
๐ท๏ธ ์บ์ ํค ๊ด๋ฆฌ - ์ฒด๊ณ์ ์ผ๋ก!
์บ์ ํค๋ฅผ ์ฒด๊ณ์ ์ผ๋ก ๊ด๋ฆฌํ๋ฉด ๋์ค์ ์ ์ง๋ณด์๊ฐ ํจ์ฌ ํธํด:
// CacheKeys.cs - ์บ์ ํค ์์ ๊ด๋ฆฌ
public static class CacheKeys
{
private const string Prefix = "myapp";
public static class Product
{
public static string ById(int id) => $"{Prefix}:product:{id}";
public static string BestSellers => $"{Prefix}:product:bestsellers";
public static string ByCategory(int categoryId) => $"{Prefix}:product:cat:{categoryId}";
}
public static class User
{
public static string ById(int id) => $"{Prefix}:user:{id}";
public static string Profile(int id) => $"{Prefix}:user:{id}:profile";
public static string Permissions(int id) => $"{Prefix}:user:{id}:perms";
}
public static class Config
{
public static string SiteSettings => $"{Prefix}:config:site";
public static string FeatureFlags => $"{Prefix}:config:features";
}
}
// ์ฌ์ฉ ์์
var product = await _cacheService.GetOrSetAsync(
CacheKeys.Product.ById(productId),
() => _repo.GetByIdAsync(productId),
TimeSpan.FromMinutes(30)
);
๐ฏ ์บ์ฑ ์ ์ฉ ์ ๋ต: ์ด๋์ ์บ์ฑ์ ์จ์ผ ํ ๊น?
์บ์ฑ์ด ์ข๋ค๊ณ ํด์ ๋ชจ๋ ๊ณณ์ ๋ค ์ฐ๋ฉด ์ ๋ผ. ์คํ๋ ค ๋ณต์ก๋๋ง ๋์์ง ์ ์์ด.
์บ์ฑ์ด ํจ๊ณผ์ ์ธ ์ํฉ๊ณผ ๊ทธ๋ ์ง ์์ ์ํฉ์ ๊ตฌ๋ถํ๋ ๊ฒ ์ค์ํด! ๐ฏ
๐ ์ฝ๊ธฐ ๋น๋๊ฐ ๋๊ณ ๋ณ๊ฒฝ์ด ์ ์ ๋ฐ์ดํฐ - ์ํ ๋ชฉ๋ก, ์นดํ ๊ณ ๋ฆฌ, ์ค์ ๊ฐ
๐ ๊ณ์ฐ ๋น์ฉ์ด ํฐ ๋ฐ์ดํฐ - ๋ณต์กํ ์ง๊ณ ์ฟผ๋ฆฌ, ํต๊ณ ๋ฐ์ดํฐ
๐ ์ธ๋ถ API ์๋ต - ๋ ์จ, ํ์จ, ์์ ๋ฏธ๋์ด ๋ฐ์ดํฐ
๐ ์ธ์ ๋ฐ์ดํฐ - ๋ก๊ทธ์ธ ์ํ, ์ฅ๋ฐ๊ตฌ๋
๐ ์ ์ ์ฝํ ์ธ - ์ด๋ฏธ์ง URL, ๊ณต์ง์ฌํญ, FAQ
๐ซ ์ค์๊ฐ์ฑ์ด ์ค์ํ ๋ฐ์ดํฐ - ์ฃผ์ ๊ฐ๊ฒฉ, ์ค์๊ฐ ์ฌ๊ณ
๐ซ ์ฌ์ฉ์๋ณ ๊ณ ์ ๋ฐ์ดํฐ - ๊ฐ์ธ ์๋ฆผ, ๋ง์ถค ์ถ์ฒ (์บ์ ํค ์ค๊ณ ์ฃผ์)
๐ซ ๋ณด์์ ๋ฏผ๊ฐํ ๋ฐ์ดํฐ - ๋น๋ฐ๋ฒํธ, ๊ฒฐ์ ์ ๋ณด
๐ซ ๋งค์ฐ ์์ฃผ ๋ณํ๋ ๋ฐ์ดํฐ - ์ฑํ ๋ฉ์์ง, ์ค์๊ฐ ์์น
์ฐธ๊ณ ๋ก, ์ฌ๋ฅ๋ท์ฒ๋ผ ๋ค์ํ ์ฌ๋ฅ์ ๊ฑฐ๋ํ๋ ํ๋ซํผ์์๋ ์บ์ฑ์ ํต์ฌ์ด์ผ.
์ฌ๋ฅ ๋ชฉ๋ก, ์นดํ
๊ณ ๋ฆฌ, ์ธ๊ธฐ ์ฌ๋ฅ ์์ ๊ฐ์ ๋ฐ์ดํฐ๋ ์บ์ฑ์ผ๋ก ์๋ต ์๋๋ฅผ ํฌ๊ฒ ๋์ผ ์ ์๊ฑฐ๋ .
๋ฐ๋ฉด ์ค์๊ฐ ์ฑํ
์ด๋ ๊ฒฐ์ ์ฒ๋ฆฌ๋ ์บ์ฑ๋ณด๋ค ๋ค๋ฅธ ์ต์ ํ ๋ฐฉ๋ฒ์ด ๋ ์ ํฉํด. ๐
๐ง .NET 8 ์ต์ ์บ์ฑ ๊ธฐ๋ฅ: HybridCache
.NET 9์์ ์ ์ ์ถ์๋๊ณ .NET 8์์ ํ๋ฆฌ๋ทฐ๋ก ์ ๊ณต๋๋ HybridCache๋ฅผ ์์๋๋ฉด ์ข์!
MemoryCache์ Redis๋ฅผ ๋์์ ํ์ฉํ๋ 2๋จ๊ณ ์บ์ฑ์ ์ฝ๊ฒ ๊ตฌํํ ์ ์์ด. ๐
// .NET 9 HybridCache ์ฌ์ฉ (Microsoft.Extensions.Caching.Hybrid)
// dotnet add package Microsoft.Extensions.Caching.Hybrid
// Program.cs
builder.Services.AddHybridCache(options =>
{
options.MaximumPayloadBytes = 1024 * 1024; // 1MB ์ต๋
options.MaximumKeyLength = 1024;
options.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(30),
LocalCacheExpiration = TimeSpan.FromMinutes(5) // L1 ์บ์ (๋ฉ๋ชจ๋ฆฌ)
};
});
// ์๋น์ค์์ ์ฌ์ฉ
public class ProductService
{
private readonly HybridCache _cache;
public ProductService(HybridCache cache)
{
_cache = cache;
}
public async Task<Product?> GetProductAsync(int id, CancellationToken ct = default)
{
// L1(๋ฉ๋ชจ๋ฆฌ) โ L2(Redis) ์์๋ก ์๋ ํ์ธ!
return await _cache.GetOrCreateAsync(
$"product:{id}",
async cancel => await _repo.GetByIdAsync(id),
cancellationToken: ct
);
}
}
โ L1 ์บ์ (๋ฉ๋ชจ๋ฆฌ) + L2 ์บ์ (Redis) ์๋ ๊ด๋ฆฌ
โ Stampede ๋ฐฉ์ง ๋ด์ฅ (๋์ ์์ฒญ ์๋ ์ฒ๋ฆฌ)
โ ํ๊ทธ ๊ธฐ๋ฐ ๋ฌดํจํ ์ง์
โ ๊ธฐ์กด
IDistributedCache์ ์๋ฒฝ ํธํโ ์ง๋ ฌํ ์๋ ์ฒ๋ฆฌ
๐ ๋ง๋ฌด๋ฆฌ: ์บ์ฑ ์ ๋ต ์ ํ ๊ฐ์ด๋
์, ์ด์ C# ์บ์ฑ์ ์ธ๊ณ๋ฅผ ๊ฝค ๊น์ด ํํํ์ด! ๐
๋ง์ง๋ง์ผ๋ก ์ด๋ค ์ํฉ์์ ์ด๋ค ์บ์ฑ ์ ๋ต์ ์ ํํด์ผ ํ๋์ง ์ ๋ฆฌํด์ค๊ฒ:
โ
IMemoryCache๋ก ์์ํด. ์ค์ ๊ฐ๋จํ๊ณ ์๋ ์ต๊ณ ์ผ.
โ
IDistributedCache + Redis๋ก ์ ํ. ๋ชจ๋ ์๋ฒ๊ฐ ๊ฐ์ ์บ์๋ฅผ ๊ณต์ ํด.
โ
StackExchange.Redis ์ง์ ์ฌ์ฉ + Redis ๊ณ ๊ธ ๊ธฐ๋ฅ ํ์ฉ.
โ
HybridCache๋ก L1+L2 ์บ์ฑ์ ํ ๋ฒ์ ํด๊ฒฐ.
โ ์บ์ ํค ์ฒด๊ณ์ ๊ด๋ฆฌ + ์ ์ ํ TTL ์ค์ + ๋ชจ๋ํฐ๋ง์ ํ์!
์บ์ฑ์ ๋จ์ํ "๋น ๋ฅด๊ฒ ๋ง๋๋ ๊ธฐ์ "์ด ์๋์ผ.
์์คํ
์ ์ฒด์ ๋ถํ๋ฅผ ๋ถ์ฐ์ํค๊ณ , ์ฌ์ฉ์ ๊ฒฝํ์ ํฅ์์ํค๋ฉฐ, ์ธํ๋ผ ๋น์ฉ์ ์ ๊ฐํ๋
์ข
ํฉ์ ์ธ ์ํคํ
์ฒ ์ ๋ต์ด์ผ. ์ฒ์์ ๋ณต์กํด ๋ณด์ฌ๋ ํ๋์ฉ ์ ์ฉํ๋ค ๋ณด๋ฉด ๊ธ๋ฐฉ ์ต์ํด์ง ๊ฑฐ์ผ! ๐ช
์ค๋ ๋ฐฐ์ด ๋ด์ฉ์ ์ ๋ฆฌํ๋ฉด:
โ IMemoryCache ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ โ Redis ์ฐ๊ฒฐ ๋ฐ ํ์ฉ โ 4๊ฐ์ง ์บ์ฑ ํจํด โ Cache Stampede/Penetration/Avalanche ๋ฐฉ์ง โ Redis ๊ณ ๊ธ ๊ธฐ๋ฅ (Hash, List, Sorted Set, ๋ถ์ฐ ๋ฝ) โ HybridCache (.NET 9) โ ์ฑ๋ฅ ๋ชจ๋ํฐ๋ง
๊ด๋ จ ํค์๋
๋๊ธ ์์ฑ
์ด ๊ธ์ ๋ํ ์ฌ๋ฌ๋ถ์ ์๊ฐ์ ๋ค๋ ค์ฃผ์ธ์
๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค
๋๊ธ์ ์์ฑํ๋ ค๋ฉด ๋จผ์ ๋ก๊ทธ์ธํด์ฃผ์ธ์.
๋๊ธ 0
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.