자주 사용하는 데이터를 더 빠른 저장소에 임시로 저장해 재사용하는 기술
Request → Cache → Miss → DB
@Cacheable / @ CacheEvict / @CachePut → Cache Abstraction Layer → CacheManager → Cache(caffeine, Redis)
// 스프링에서 캐시 사용할 것임
implementation 'org.springframework.boot:spring-boot-starter-cache'
// 캐시는 로컬 캐시 : caffeine을 사용할 것임
implementation 'com.github.ben-manes.caffeine:caffeine'
@SpringBootApplication
@EnableCaching // 캐시 기능 활성화 -> 없으면 캐시 활성화 안됨
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
spring:
cache:
caffeine:
spec: maximumSize=100,expireAfterWrite=10s
# 최대 100개 캐시 유지, 10초 후 만료
# 이것 이외에도 정말 다양한 TTL & Eviction Policy 있으니 다양한 옵션을 알고 싶으면
# 공식 문서를 참고해주세요!
@Cacheable(value = "postCache", key = "'id:' + #postId")
public PostDto getPostById(long postId) {
log.info("캐시에 없으니 DB에서 직접 조회");
Post post = postRepository.findById(postId)
.orElseThrow(() -> new IllegalArgumentException("등록된 포스트가 없습니다."));
return PostDto.from(post);
}
@CacheEvict(value = "postCache", key = "#postId")
public void deletePost(long postId) {
// post 삭제 로직
}
@CachePut(value = "postCache", key = "#postId")
public PostDto updatePost(long postId) {
// post 업데이트 로직
}