본문 바로가기

Web/spring

[Spring Boot IO] 1. Caching

728x90

https://docs.spring.io/spring-boot/docs/current/reference/html/io.html#io

 

IO

The Spring Framework provides support for transparently adding caching to an application. At its core, the abstraction applies caching to methods, thus reducing the number of executions based on the information available in the cache. The caching logic is

docs.spring.io

틀린 내용이 있다면 알려주세요 🐈‍⬛

 

 


IO 설명부터

대부분의 application 은 어느 시점에서 입출력 문제에 대한 처리를 해야한다

이에 대한 다양한 유틸리티를 안내한다

 

 IO features such as caching and validation as well as more advanced topics such as scheduling and distributed transactions. We will also cover calling remote REST or SOAP services and sending email.

 

 

 

이번 살펴볼 내용은 캐싱!

 

1. Caching

Cache Abstraction을 이용하여 mehod에 캐싱을 적용하여 사용가능한 정보를 실행하는 횟수를 줄인다.

Spring Boot는 @EnableCaching 애노테이션을 사용하여 캐싱 지원이 활성화 되어있는 한 캐시 인프라를 자동 구성해준다

 

 

내가 정리한 CacheAbstraction(1)

https://delightpip.tistory.com/86

내가 정리한 CacheAbstraction(2)

https://delightpip.tistory.com/97

 

 

캐싱추가 예시

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class MyMathService {

    @Cacheable("piDecimals")
    public int computePiDecimal(int precision) {
        ...
    }

}

캐싱은 잠재적으로 costly opration 한 작업들에 주로 이용된다. ComputePiDecimal 호출 전에 이 캐시 abstraction이 i 인수와 일치하는 piDecimals 캐시에서 내용을 찾는다. 발견되면 캐시의 컨텐츠가 호출자에게 즉시 반환하고 메소드 호출을 막는다. 만약 발견하지 못하면 메서드가 호출되어 값을 반환하기 전에 캐시가 업데이트 된다.

 

 

특정 캐시라이브러리르 추가하지않더라도 메모리에서  concurrent maps in memory 을 사용하는 Simple provider을 auto-configures해준다.  https://docs.spring.io/spring-boot/docs/current/reference/html/io.html#io.caching.provider.simple 

캐시가 필요한 경우(piDecimals 앞의 예) 이 공급자는 캐시를 생성한다.

 

 

1.1. Supported Cache Providers

The cache abstraction does not provide an actual store and relies on abstraction materialized by the org.springframework.cache.Cache and org.springframework.cache.CacheManager interfaces.

If you have not defined a bean of type CacheManager or a CacheResolver named cacheResolver (see CachingConfigurer), Spring Boot tries to detect the following providers (in the indicated order):

 

CachingConfigurer

https://docs.spring.io/spring-framework/docs/6.0.5/javadoc-api/org/springframework/cache/annotation/CachingConfigurer.html

 

CachingConfigurer (Spring Framework 6.0.5 API)

Return the CacheResolver bean to use to resolve regular caches for annotation-driven cache management. This is an alternative and more powerful option of specifying the CacheManager to use. If both a cacheManager() and #cacheResolver() are set, the cache m

docs.spring.io

 

이 중에서 몇 개만 살펴볼예정

 

 

Generic 

JCache (JSR107) (EhCache 3, Hazelcast, Infinispan, and others)

Hazelcast

Infinispan

Couchbase

Redis

Caffeine

Cache2k

Simple

또한, 아파치 Geode용 에서도 geode-caching-provider 를 지원한다고 한다 

https://docs.spring.io/spring-boot-data-geode-build/2.0.x/reference/html5/#geode-caching-provider

 

Spring Boot for Apache Geode Reference Guide

The state of modern software application development is moving towards containerization. Containers offer a controlled environment to predictably build (compile, configure and package), run, and manage your applications in a reliable and repeatable manner,

docs.spring.io

 

Spring Boot for Apache Geode Reference Guide

The state of modern software application development is moving towards containerization. Containers offer a controlled environment to predictably build (compile, configure and package), run, and manage your applications in a reliable and repeatable manner,

docs.spring.io

 

 

Spring Boot 에 의해 auto-configures 을 사용할 경우에 아예 CacheManager 인터페이스로 구현한 CacheManagerCustomizer  bean을 노출하여 초기화 전에 구성을 조정할 수 있다. 

 

@Configuration(proxyBeanMethods = false)
public class MyCacheManagerConfiguration {

    @Bean
    public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
        return (cacheManager) -> cacheManager.setAllowNullValues(false);
    }

}

위의 예시에서 auto-configures된 ConcurrentMapCacheManager가 필요하다. 그렇지 않은 경우(자체 구성을 제공했거나 다른 캐시 공급자가 자동 ​​구성됐을 때) 전혀 호출되지 않는다. customizers는 원하는 만큼 가질 수 있으며 @Order 또는 Ordered를 사용할 수 있다.

 

 

1.1.1. Generic

 

일반적인 캐싱

Generic caching is used if the context defines at least one org.springframework.cache.Cache bean. A CacheManager wrapping all beans of that type is created.

 

 

 

1.1.6. Redis

https://redis.io/

 

Redis

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker

redis.io

 

Redis 를 사용하기 위해 구성할 경우 RedisCacheManager가 auto-configures 된다

create additional caches on startup by setting the spring.cache.cache-names property and cache defaults can be configured by using spring.cache.redis.* properties. 

 

 

 

configuration creates cache1 and cache2 caches with a time to live of 10 minutes

 

properties

spring.cache.cache-names=cache1,cache2
spring.cache.redis.time-to-live=10m

 

Redis의 RedisCacheManager는 기본적으로 두개의 별도 캐시가 동일한 키를 사용할 경우 겹치는 키를 갖지 않고 유효하지않은 값을 반환할 수 없도록 키 접두사를 추가시킨다.

@ RedisCacheConfiguration @Bean 을 이용하여 기본 구성을 완전히 제어할 수 있다

customize the default serialization strategy 직렬화 커스터마이징에 유용할 수  있다

 

 

구성에 대한 제어가 많이 필요할 경우에는

RedisCacheManagerBuilderCustomizer bean을 등록하면 된다

 

@Configuration(proxyBeanMethods = false)
public class MyRedisCacheManagerConfiguration {

    @Bean
    public RedisCacheManagerBuilderCustomizer myRedisCacheManagerBuilderCustomizer() {
        return (builder) -> builder
                .withCacheConfiguration("cache1", RedisCacheConfiguration
                        .defaultCacheConfig().entryTtl(Duration.ofSeconds(10)))
                .withCacheConfiguration("cache2", RedisCacheConfiguration
                        .defaultCacheConfig().entryTtl(Duration.ofMinutes(1)));

    }

}

 

 

 

 

1.1.7. Caffeine

https://github.com/ben-manes/caffeine

 

GitHub - ben-manes/caffeine: A high performance caching library for Java

A high performance caching library for Java. Contribute to ben-manes/caffeine development by creating an account on GitHub.

github.com

 

Caffeine은 Guava에 대한 지원을 대체하는 Guava 캐시의 JAVA 8 rewite 이다

 If Caffeine is present, a CaffeineCacheManager (provided by the spring-boot-starter-cache “Starter”) is auto-configured. Caches can be created on startup by setting the spring.cache.cache-names property and can be customized by one of the following (in the indicated order):

  1. A cache spec defined by spring.cache.caffeine.spec
  2. A com.github.benmanes.caffeine.cache.CaffeineSpec bean is defined
  3. A com.github.benmanes.caffeine.cache.Caffeine bean is defined
spring.cache.cache-names=cache1,cache2
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s

 

com.github.benmanes.caffeine.cache.CacheLoader의 빈이 자동 정의 되면 CaffeineCacheManager로 자동연결된다

CacheLoader는 캐시관리자가 관리하는 모든 캐시에 연결되므로 CacheLoader<Object, Object>로 정의 해야하고, 자동구성일 경우 다른 일반 유형을 무시한다

 

1.1.9. Simple

다른 providers가 없을 경우 ConcurrentHashMap을 캐시 storage로 사용하는 Simple implementation이 구성된다
캐싱 라이브러리가 없는 경우 기본값이며, 캐시가 필요에 따라 생성된다.
cache-names 속성을 설정하여 사용가능한 캐시 목록을 제한할 수 있다.
 
spring.cache.cache-names=cache1,cache2
이렇게 하면 저기 적용 안된 캐시를 사용한다면 런타임에서는 오류 없이 실행되지만 적용안된 캐시를 실제로 사용하려고 할때 실패된다.
 
 

1.1.10. None

@EnableCaching 이 있으면 적절한 캐시 구성이 이루어진다. 개발하는 중에는 특정환경에서 캐싱을 모두 비활성해야할 수도 있다.

그럴땐 이렇게 하면 됨

 

spring.cache.type=none
 
728x90