본문 바로가기

Spring Boot/Cache

Spring Cache 추상화 : Spring Boot 캐시 자동 설정

스프링부트 캐시 자동..? 설?정

 

 - Spring Boot의 자동 설정(Auto Configuration) 원리

 - CacheManager의 기본 설정이 자동으로 적용되는 과정

 - 다양한 캐시 구현체(Caffeine, EnCache, Redis 등등..)가 자동으로 감지되는 구조

 - application.yml을 활용하여 캐시 속성을 설정하고 커스터마이징 하는법

 - 실무에서 캐시 설정을 분리하고 관리하는 패턴

 


Spring Boot 캐시 자동 설정 개요

Spring Boot에서는 별도의 설정 없이 자동으로 캐시 환경을 구성함

spring-boot-starter-cache 의존성을 추가하면

@EnableCaching 애너테이션을 통해 자동으로 캐시 관련 Bean(CacheManager, CacheResolver)이 등록된다

// cache
implementation 'org.springframework.boot:spring-boot-starter-cache'

// caffeine
implementation 'com.github.bean-manes.caffeine:caffeine'

 

Spring Boot Cache Auto Configuration/

 > CacheAutoConfiguration/

 > > CacheManager Customizers

 > > CacheProperties

 > > CacheConfiguration Import

 > 지원 캐시 구현체 자동 감지/

 > > CaffeineCacheConfiguration

 > > EnCacheCacheConfiguration

 > > RedisCacheConfiguration

 > > SimpleCacheConfiguration

 


기본 캐시 매니저 설정

Spring Boot는 기본적으로 CacheManager Bean을 자동으로 생성한다

캐시 구현체가 명시되지 않은 경우, ConcurrentMapCacheManager가 기본으로 등록된다

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class CacheTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheTestApplication.class, args);
    }
}

 

이 설정만으로 캐싱 기능이 자동 활성화된다고 한다.

* Configuration별로 @EnableCaching을 명시하여 분리하여 사용할 수도 있다

 

별도의 CacheManager Bean을 정의하지 않으면 Spring Boot는 아래와 같은 순서대로 구현체를 자동 탐색한다고 한다.

우선순위 캐시 구현체 자동 설정 클래스
1 Redis RedisCacheConfiguration
2 Caffeine CaffeineCacheConfiguration
3 EnCache EnCacheCacheConfiguration
4 Simple Map SimpleCacheConfiguration

 

 

2. 실제 동작 구조

Spring Boot Cache 동작 구조

 

Spring Boot에서는 ClassPath 상에 존재하는 라이브러리를 감지하여, 자동으로 CacheManager를 구성해준다고 한다.

 

 


캐시 구현체 자동 감지

Spring Boot는 아래와 같은 캐시 구현체를 자동으로 감지해준다

구현체 의존성 설명
Caffeine spring-boot-starter-cache
com.github.bean.manes.caffeine
고성능 인메모리 캐시
EnCache net.sf.encache:encache 디스크 기반 영속 캐시
Redis spring-boot-starter-data-redis 분산 캐시 및 공유 환경에서 적합

 

 

1. Caffeine 예시

 

build.gradle

// build.gradle에 implementation
implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'com.github.ben-manes.caffeine:caffeine'

 

application.yml

spring:
  cache:
    type: caffeine
    cache-names: userCache, productCache
    caffeine:
      spec: maximumSize=1000, expireAfterWrite=10m

 

Spring Boot는 위 설정을 자동으로 감지하여, CaffeineCacheManager를 생성한다고 함

 

 

2. Redis 예시

 

build.gradle

// redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'

 

application.yml

spring:
  cache:
    type: redis
    cache-names: sessionCache, userCache
    redis:
      time-to-live: 600000 # 캐시 TTL(10분, ms)
      key-prefix: myapp::
      use-key-prefix: true

 

자동으로 RedisCacheManager가 생성되며, spring.cache.redis 속성을 기반으로 TTL, prefix, serialization 설정이 적용된다!

 


속성 기반 설정 방법

Spring Boot에서는 application.yml 또는 application.properties를 통해 캐시를 쉽게 구성할 수 있다고 한다.

속성 설명 예시
spring.cache.type 사용할 캐시 구현체 지정 caffeine / redis / simple
spring.cache.cache-names 캐시 이름 목록 userCache, productCache
spring.cache.caffeine.spec Caffeine 전용 설정 expireAfterWrite=10m
spring.cache.redis.time-to-live Redis TTL(ms) 600000
spring.cache.redis.key-prefix Redis 키 접두사 myapp::

 

 

1. 예제 : 다중 캐시 조합 설정(Caffeine, Redis)

 

application.yml

spring:
  application:
    name: CacheTest
  cache:
    cache-names: userCache, productCache, orderCache
    caffeine:
      spec: maximumSize=500, expireAfterWrite=5m
    redis:
      time-to-live: 300000

 

 

CacheConfig.java

import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.support.CompositeCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // Redis + Caffeine 하이브리드 CacheManager 구성 예시임
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory).build();
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager("localCache");

        // CompositeCacheManager를 통해 다중 캐시 매니저 관리를 함
        CompositeCacheManager compositeCacheManager = new CompositeCacheManager(caffeineCacheManager, redisCacheManager);
        compositeCacheManager.setFallbackToNoOpCache(true);
        return compositeCacheManager;
    }
}

 


기본 설정 커스터마이징

Spring Boot 자동 설정은 그대로 사용하되, 특정 속성만 수정하거나 확장할 수 있다고 한다.

 

1. CacheCustomizer 활용

 

CacheCustomizerConfig implements CacheManager<T extends CacheManager>

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class CacheCustomizerConfig implements CacheManagerCustomizer<CaffeineCacheManager> {
    @Override
    public void customize(CaffeineCacheManager cacheManager) {
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .maximumSize(2000)
                .expireAfterAccess(15, TimeUnit.MINUTES));
    }
}

 

CacheManagerCustomizer는 자동 구성된 캐시 매니저에 추가 설정을 덧붙일 수 있는 일종의 훅(Hook)이다!

 


* 자동 설정을 그대로 사용하는 경우, 기본 캐시 전략(SimpleCache)이 적용된다고 한다.

* Redis나 Caffeine처럼 외부 라이브러리를 사용할 땐 반드시 의존성 추가 + yml에 spring.cache.type 지정이 필요하다.

* CompositeCacheManager를 사용하면 로컬 캐시 + 분산 캐시를 병행할 수 있다고 한다.(CacheManager 안에 Composite)

* 운영 환경에서는 TTL과 캐시 크기 설정을 명확하게 수치화 해야함

* 캐시 설정은 환경별(application-dev.yml(개발), application-prod.yml(배포))로 분리 관리하는게 좋다고 함

 


정리

구분 설명 예시
기본 CacheManager ConcurrentMapCacheManager 자동 생성 설정이 없으면 기본 적용
자동 감지 구현체 Redis, Caffeine, EnCache 등.. 의존성 감지 후 자동 설정
속성 기반 설정 application.yml에서 직접 지정함 spring.cache.*
커스터마이징 CacheManagerCustomizer,
CompositeCacheManager(분산캐시)
다중 캐시 구성