API 요청으로 데이터가 반환되는 경우 특정 키 기준으로 동일한 데이터가 반환된다면 ResponseCache를 활용하면 응답 데이터를 캐싱하여 서버 부하를 줄일 수 있습니다. 이를 활용하는 방법을 알아봅니다.
using Microsoft.OpenApi.Models;
namespace WebApiCacheTest
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
// ResponseCaching 설정
builder.Services.AddResponseCaching(options =>
{
// 캐시할 수 있는 응답 본문의 최대 크기를 100MB로 설정
options.MaximumBodySize = 100 * 1024 * 1024; // 100MB
// 전체 응답 캐시의 최대 크기
options.SizeLimit = 50 * 1024 * 1024; // 50MB
// URL 경로의 대소문자 구분 여부
options.UseCaseSensitivePaths = true;
});
// Swagger 서비스 등록
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Caching API 예제",
Version = "v1",
Description = "Response Cache와 Memory Cache 예제를 보여주는 API"
});
});
var app = builder.Build();
// Swagger 미들웨어 설정
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Caching API v1");
c.RoutePrefix = string.Empty; // 루트 URL에서 Swagger UI 제공
c.DisplayRequestDuration(); // 요청 지속 시간 표시
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseHttpsRedirection();
app.UseAuthorization();
// ResponseCaching 설정
app.UseResponseCaching();
app.MapControllers();
app.Run();
}
}
}
using Microsoft.AspNetCore.Mvc;
namespace WebApiCacheTest.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
[HttpGet("GetData/{key}")]
[ResponseCache(Duration = 30, Location = ResponseCacheLocation.Any, VaryByQueryKeys = new[] { "key" })]
public IActionResult GetWithResponseCache(string key)
{
return Ok(new
{
key = key,
message = $"Response Cache Test for key: {key}",
timestamp = DateTime.Now.ToString()
});
}
}
실행결과
Any 로 설정되어 있어 동일한 데이터가 반환됩니다.
오른쪽 응답 헤더를 보면 아래와 같은데
age: 1
cache-control: public,max-age=30
content-length: 95
content-type: application/json; charset=utf-8
date: Tue,25 Feb 2025 14:02:58 GMT
server: Kestrel
이는 cache-control 을 보면 알 수 있듯이 캐싱된 데이터가 반환된 것임을 알수 있습니다.
CSnakes.Runtime 을 로컬 파이썬/VM 이용하기 (0) | 2025.01.25 |
---|---|
CSnakes.Runtime 사용하기 (0) | 2025.01.22 |
NuGet 패키지 소스 매핑으로 패키지 설치 오류 해결하기 (0) | 2025.01.18 |
LM-Kit.NET 활용하기 (0) | 2024.10.27 |
C# 키보드 후킹하기 (0) | 2024.10.21 |