728x90
캐시란?
동일한 요청에 대해, 기존에 계산한 결과를 재사용해 응답 속도를 향상시키는 기술
캐시 | 위치설명 |
메모리(Local) | 서버 내 메모리에 저장, 간단하고 빠름 |
Redis 등 외부 캐시 | 분산 캐시, 다수 서버에서 공유 가능 |
1. Spring Boot 캐시 기본 설정
의존성 추가 (Spring Boot Starter Cache)
implementation 'org.springframework.boot:spring-boot-starter-cache'
@EnableCaching 설정 추가
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
2. 기본 캐시 애너테이션 사용법
@Cacheable – 결과를 캐시에 저장
@Cacheable(value = "member", key = "#id")
public Member getMemberById(Long id) {
simulateSlowService();
return memberRepository.findById(id).orElse(null);
}
파라미터 | 설명 |
value | 캐시 이름 (분류용) |
key | 저장할 캐시 키 (EL 표현식 사용 가능) |
같은 ID로 요청하면 DB 조회 없이 캐시에서 바로 반환됩니다.
@CachePut – 항상 실행 + 결과는 캐시에 저장
@CachePut(value = "member", key = "#member.id")
public Member updateMember(Member member) {
return memberRepository.save(member);
}
@CacheEvict – 캐시 삭제
@CacheEvict(value = "member", key = "#id")
public void deleteMember(Long id) {
memberRepository.deleteById(id);
}
allEntries = true 옵션으로 해당 캐시 전체 삭제도 가능
3. 캐시 매니저 설정 (Optional)
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("member", "post", "product");
}
4. Redis 캐시로 확장하기 (실무용)
Redis 의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
application.yml 설정
spring:
cache:
type: redis
redis:
host: localhost
port: 6379
RedisCacheManager 자동 적용됨
- 기본적으로 RedisCacheConfiguration이 자동 등록되어 TTL(만료시간) 설정도 가능
캐시 key 커스터마이징
@Cacheable(value = "userCache", key = "'User::' + #email")
SpEL(Spring Expression Language)을 이용해 문자열 조합 가능
캐시 적용 시점 판단 기준
적용 위치 |
예시 |
API 응답 | 조회 빈도가 높고 변경이 적은 데이터 |
JPA 서비스 | 동일 쿼리 반복 시 (e.g. 인기글, 베스트상품) |
3rd Party API | 느린 외부 API 호출 결과 |
주의할 점
항목 | 설명 |
트랜잭션 내부 | 캐시는 트랜잭션 커밋 이후에 적용됨 |
DTO 매핑 | 캐시 대상 객체는 Serializable을 구현해야 안전함 |
만료 정책 | TTL(Time To Live) 설정 고려해야 메모리 낭비 방지 |
마무리 요약
항목 | 설명 |
기본 사용 | @Cacheable, @CachePut, @CacheEvict |
캐시 저장소 | 기본: ConcurrentMap, 실무: Redis |
커스터마이징 | key 표현식, TTL 설정, 캐시 이름 지정 가능 |
확장 | Redis, Caffeine, Hazelcast 등 지원 가능 |
LIST
'SpringBoot > 심화 주제' 카테고리의 다른 글
마이크로서비스 아키텍처(MSA) 입문 (1) | 2025.04.16 |
---|---|
멀티모듈 프로젝트 구성 (0) | 2025.04.16 |
WebSocket & 실시간 알림 (0) | 2025.04.16 |
QueryDSL (0) | 2025.04.16 |