TIL - 26.02.25

이준연·2026년 2월 24일

Cache


자주 사용하는 데이터를 더 빠른 저장소에 임시로 저장해 재사용하는 기술

  • DB나 외부 API 호출 없이 메모리에서 즉시 응답 가능
  • 핵심 목적: 속도 향상, DB 부하 감소, 트래픽 절감

기본 구조

Request → Cache → Miss → DB

Spring Cache

  • Spring이 제공하는 캐싱 추상화
@Cacheable / @ CacheEvict / @CachePut → Cache Abstraction Layer → CacheManager → Cache(caffeine, Redis)

build.gradle

// 스프링에서 캐시 사용할 것임
implementation 'org.springframework.boot:spring-boot-starter-cache' 

// 캐시는 로컬 캐시 : caffeine을 사용할 것임
implementation 'com.github.ben-manes.caffeine:caffeine' 

Application.java

@SpringBootApplication
@EnableCaching // 캐시 기능 활성화 -> 없으면 캐시 활성화 안됨
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

application.yml

spring:
  cache:
    caffeine:
      spec: maximumSize=100,expireAfterWrite=10s
# 최대 100개 캐시 유지, 10초 후 만료
# 이것 이외에도 정말 다양한 TTL & Eviction Policy 있으니 다양한 옵션을 알고 싶으면
# 공식 문서를 참고해주세요!

@Cacheable - DB 조회 후 캐시 저장, 이후 동일한 요청 시 캐시에서 바로 반환

@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 - 캐시 삭제

@CacheEvict(value = "postCache", key = "#postId")
public void deletePost(long postId) {
		// post 삭제 로직
}

@CachePut - 캐시 갱신

@CachePut(value = "postCache", key = "#postId")
public PostDto updatePost(long postId) {
		// post 업데이트 로직
}
profile
반갑습니다!

0개의 댓글