Spring Cache로 API 3배 빠르게(@Cacheable/무효화)
읽기 많은 API는 캐시만 잘 얹어도 체감 속도가 크게 개선됩니다. 스프링 캐시 추상화는 구현(Caffeine/Redis 등)을 바꿔도 코드가 단순합니다.
의존성(Caffeine 예)
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
설정
@EnableCaching
@Configuration
public class CacheConfig {
@Bean CacheManager cacheManager() {
CaffeineCache user = new CaffeineCache("userById",
Caffeine.newBuilder().maximumSize(10_000).expireAfterWrite(Duration.ofMinutes(10)).build());
return new SimpleCacheManager() {{ setCaches(List.of(user)); }};
}
}
사용
@Cacheable(cacheNames="userById", key="#id")
public User getUser(long id) {
simulateSlow(); // DB 호출 등
return repo.findById(id).orElseThrow();
}
@CacheEvict(cacheNames="userById", key="#id")
public void updateUser(long id, UserUpdate req) { ... }
운영 팁
- 키 전략: 멀티 파라미터는
key="#root.args"또는 SpEL 조합 - 동시성 보호: cache stampede 방지(서킷/스로틀, Caffeine
refreshAfterWrite) - 강제 갱신:
@CachePut로 캐시와 소스 동기화
FAQ
Q1. 분산 캐시가 필요하면?
A. RedisCacheManager로 교체하고 TTL/직렬화 설정을 추가하세요.
Q2. 조건부 캐시?
A. condition / unless 속성으로 캐시 여부를 제어할 수 있습니다.
👉 1편: Bean Validation(@Valid)로 입력 검증 표준 만들기
👉 2편: @ControllerAdvice 글로벌 예외 응답(에러코드 규격)
👉 3편: application-{profile}.yml 전략 + 비밀키 분리
👉 4편: Spring Boot Actuator: /health 커스터마이징
👉 5편: @Scheduled 크론 12패턴 + 중복실행 방지
'Java & Spring' 카테고리의 다른 글
| Maven→Gradle 마이그레이션 함정 7가지 (0) | 2025.10.01 |
|---|---|
| Pageable 응답 DTO 규격(정렬·페이지 표준화) (0) | 2025.09.30 |
| 멀티파트 업로드: 제한/보안/임시저장 설계 (0) | 2025.09.30 |
| @Scheduled 크론 12패턴 + 중복실행 방지 (0) | 2025.09.30 |
| Spring Boot Actuator: /health 커스터마이징 (0) | 2025.09.30 |