.NET Core는 두 가지 독립적인 캐싱 프레임워크를 제공합니다. 하나는 로컬 메모리를 위한 캐싱이며, 다른 하나는 분산 저장소를 위한 캐싱입니다. 전자는 현재 애플리케이션 프로세스의 메모리에 객체를 직접 저장하므로 직렬화가 필요하지 않지만, 후자는 객체를 바이트 배열로 직렬화하여 독립적인 "중앙 데이터베이스"에 저장해야 합니다. 분산 캐싱의 경우, .NET Core는 Redis와 SQL Server에 대한 네이티브 지원을 제공합니다. 이 두 가지 독립적인 캐싱 시스템 외에도, ASP.NET Core는 미들웨어를 통해 응답 캐싱(Response Caching)을 구현하며, 이는 HTTP 캐싱 규격에 따라 전체 응답 콘텐츠를 캐싱하는 방식입니다.
- 메모리 기반 캐싱 프레임워크는 NuGet 패키지 "Microsoft.Extensions.Caching.Memory"에 구현되어 있으며, 실제 캐싱 기능은 IMemoryCache 인터페이스로 표현되는 서비스 객체에 의해 담깁니다. 캐싱된 데이터가 메모리에 직접 저장되고 지속성 저장소와 관련이 없으므로 캐싱 객체에 대한 직렬화 문제를 고려할 필요가 없으며, 이러한 메모리 모드는 캐싱 데이터의 유형에 대한 제한이 없습니다.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
var builder = WebApplication.CreateBuilder(args);
// 메모리 캐싱 서비스 등록
builder.Services.AddMemoryCache();
var app = builder.Build();
app.Use(async (context, next) =>
{
var cache = context.RequestServices.GetRequiredService<IMemoryCache>();
if (!cache.TryGetValue("currentTime", out string cachedTime))
{
var newTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
cache.Set("currentTime", newTime);
await context.Response.WriteAsync($"새로운 시간이 캐시되었습니다: {newTime}");
}
else
{
await context.Response.WriteAsync($"캐시된 시간: {cachedTime}");
}
await next();
});
app.Run();
테스트 결과
Redis 분산 캐싱 프레임워크는 NuGet 패키지 "Microsoft.Extensions.Caching.Redis"에 포함되어 있으며, 해당 NuGet 패키지의 종속성을 수동으로 추가해야 합니다.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
var builder = WebApplication.CreateBuilder(args);
// Redis 분산 캐싱 서비스 등록
builder.Services.AddDistributedRedisCache(options =>
{
options.InstanceName = "myAppCache";
options.Configuration = "localhost:6379";
});
var app = builder.Build();
app.Use(async (context, next) =>
{
var distributedCache = context.RequestServices.GetRequiredService<IDistributedCache>();
var cachedTime = await distributedCache.GetStringAsync("currentTime");
if (string.IsNullOrEmpty(cachedTime))
{
var newTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var cacheOptions = new DistributedCacheEntryOptions
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(1),
SlidingExpiration = TimeSpan.FromSeconds(30)
};
await distributedCache.SetStringAsync("currentTime", newTime, cacheOptions);
await context.Response.WriteAsync($"새로운 시간이 Redis에 저장되었습니다: {newTime}");
}
else
{
await context.Response.WriteAsync($"Redis에서 가져온 캐시된 시간: {cachedTime}");
}
await next();
});
app.Run();