Undergoing

Spring Boot Caffeine 기본 세팅 본문

개발/Spring Boot

Spring Boot Caffeine 기본 세팅

Halkrine 2021. 6. 24. 14:56

1. 의존성 추가

pom.xml

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
      <version>2.4.3</version>
    </dependency>
    <dependency>
      <groupId>com.github.ben-manes.caffeine</groupId>
      <artifactId>caffeine</artifactId>
      <version>3.0.2</version>
    </dependency>



gradle

implementation group: 'org.springframework.boot', name: 'spring-boot-starter-cache', version: '2.4.3'
implementation group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.0.2'




2. Bean 세팅

@Configuration
@EnableCaching
public class CacheConfig {

    private static final int DEFAULT_MAXSIZE = 1000;
    private static final int DEFAULT_TTL = 3600;

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager manager = new SimpleCacheManager();

        ArrayList<CaffeineCache> caches = new ArrayList<>();
        for (Caches c : Caches.values()) {
            caches.add(new CaffeineCache(c.name(),
                    Caffeine.newBuilder().recordStats().expireAfterAccess(c.getTtl(), TimeUnit.SECONDS)
                            .expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)
                            .maximumSize(c.getMaxSize()) // entry 갯수
                            .build())
            );
        }
        manager.setCaches(caches);
        return manager;
    }

    public enum Caches {
        tempCache(30)        // 사용할 캐시들 입력
        , tempCache1(40)     // Example : cacheName(TTL, maxSize)

        , ...;

        private int maxSize = DEFAULT_MAXSIZE;
        private int ttl = DEFAULT_TTL;

        Caches() {
        }

        Caches(int ttl) {
            this.ttl = ttl;
        }

        Caches(int ttl, int maxSize) {
            this.ttl = ttl;
            this.maxSize = maxSize;
        }

        public int getMaxSize() {
            return maxSize;
        }

        public void setMaxSize(int maxSize) {
            this.maxSize = maxSize;
        }

        public int getTtl() {
            return ttl;
        }

        public void setTtl(int ttl) {
            this.ttl = ttl;
        }
    }
}


3. application.yml 세팅
- bean 만들면 application.yml에 굳이 세팅 필요없는 것 같음. 사실 yaml 활용하고 싶었지만 레퍼런스들 참고하다가 나온 최종 상태가 결국 클래스 파일 하나를 두어 관리하게 되어 버림

- 세팅 시 다음과 같은 형식으로 기본 옵션 정도는 처리 가능

 

spring:
 cache:
    caffeine:
      spec: maximumSize=500,expireAfterAccess=20s
      type: caffeine
      cache-names:
        - testCache
        - testCache1

* 구현할 때에는 뭐든지 상관없지만, 코드화해서 관리하는 걸 권장함

https://programmersought.com/article/66363628633/


 

spring boot caffeine - Programmer Sought

Guava cache was canceled as a local cache in spring 5. Caffeine is recommended. For specific reasons, please refer to the official website test parameters. org.springframework.boot spring-boot-starter-cache com.github.ben-manes.caffeine caffeine spring.cac

programmersought.com

4. usage

// value = cache 저장소, key = 저장소 key값
@Cacheable(value = "tempCache", key = "'tempCache'.concat(#usrId)")
public List testList(String usrId){
	...
}

 

고려 사항

- 여러 개의 캐시 및 키 관리법 중 뭐가 나을까

https://github.com/spring-projects/spring-framework/issues/15586

 

@CacheEvict should allow multiple key values [SPR-10958] · Issue #15586 · spring-projects/spring-framework

Ashot Golovenko opened SPR-10958 and commented Currently you can evict only one or all elements in a single cache region. Allowing something like @CacheEvict(value = "userCache", key = {&...

github.com

- 찾아보니 여러 방법으로 Caffeine(등 여러 Cache 기법)을 구축하는데 하다 보니 config class를 따로 만들었는데, 좀 더 생산적인 방법이 있을까

 

- cache만 모아두고 만료시간 전에 캐시값 변조 후 재적재가 가능할까, 그 과정이 필요할까