[Spring] Cache

Spring framework에서는 기본적으로 Hash map 기반의 cache 기능을 지원한다. 이번 글에서는 Spring의 cache기능에 대하여 전반적으로 알아보고 간단하게 사용해 보려고 한다.

JAVA에서의 Cache

JAVA에서는 CachingProvider, CachManager, Cashe, Entry, Expity등 5개의 Interface을 제공한다.

CachingProvider: CacheManager를 정의 및 구성, 관리를 해주는 interface 정의

CacheManager: 하나의 Cache에 대한 관리 interface 정의 , 하나의 CacheManager는 하나의 CachingProvider만 소유할 수 있다.

Cache: Key-value Mapping 관계를 가진 자료구조이다.

Entry: Cache에 저장된 key-value 쌍을 말한다.

Expiry: Cache 속 entry들의 유효기간을을 관리하는 interface이다.

* 소개한 Interface는 JSR-107에 정의되여 있다.

Spring에서의 cache

Spring 3.1부터 JSR-107의 interface를 지원하여 Spring에서 보다 쉽게 cache를 구현 할 수 있게 만들었다.

Spring Cache 용어 정리

Cache Cache interface를 정의, 구현체로는 Redis, Ehcache, ConcurrentMap 등이 있다.
CacheManager Cache 관리자, Cache 생성부터, 설정 등을 관리한다.
@Cacheable Method에 대하여 cache를 적용할때 사용된다.
@CachePut Cache 데이터를 저장할때 사용, 보통 무조건 Caching하고 싶은 데이터 대하여 사용한다.
@CacheEvict Cache를 지운다
@EnableCaching Cache 기능을 활성화
KeyGenerator Key 생성함수, 커스텀 키를 생성할 수 있도록 정의 할 수 있다
serilazize value에 대한 시리얼라이즈 방법에 대해 정의 할 수 있다.

Gradle 설정

implementation("org.springframework.boot:spring-boot-starter-cache:2.6.2")

Spring의 기본 Cache를 사용하려면 위의 dependency를 추가해 주면 된다.

@EnableCaching 사용

Caching 기능을 활성화하기 위해서는 @Enablecaching 어노테이션을 사용해야 한다.

@EnableCaching
@SpringBootApplication
class DispatchApplication

fun main(args: Array<String>) {
    runApplication<DispatchApplication>(*args)
}

생성 시 옵션으로 아래와 같은 값을 줄 수 있다.

Proxy-target-class(false): proxy모드에만 적용된다, @Cachable나 @CacheEvict 이노테이션 붙은 함수에서 어떤 종류의 캐싱 프록시를 사용할지를 제어한다.

mode(proxy): 기본값으로 설정되면 AOP프레임워크 기반의 빈을 프록시한다. 이 모드에서는 class 내에서의 서로 호출은 않된다. 만약 자기호출을 원한다면 aspectj 방식을 사용할것을 고려해야 한다.

order: 캐시 어브바이스 순서를 정의한다.

사용

//기본 사용, 입력 parameter 기반으로 caching 한다.
@Cacheable("upper")
fun getUpper(param: String): String {
    Thread.sleep(1000)
    return param.toUpperCase()
}
//Spel를 사용하여 키 정의
@Cacheable(key ="#dtoUser.id")
fun login_user(dtoUserLogin: DTOUserLogin): ResponseEntity<*>

//값을 cache에 저장, 초기화 시 사용하면 좋음
@CacgePut()
fun getUser(userId:String)

//캐시에서 사제
@CacheEvict()
fun deleteUser(userId:String)

//unless 조건, 조건 만족 시 저장 않함
@Cacheable(key ="#dtoUser.id", unless="#userId==10")
fun deleteUser(userId:String)

Ref:

https://jsonobject.tistory.com/604

https://jsonobject.tistory.com/441

https://hazelcast.com/glossary/jcache-java-cache/

https://medium.com/@itasyurt/how-to-customize-caches-with-spring-spring-boot-de801d5ecf38

https://12bme.tistory.com/550

'Spring boot' 카테고리의 다른 글

AWS SES 사용하기  (0) 2022.03.01
[Spring] 코드에서 Active Profile 가져오기  (0) 2022.01.09
[Spring] Maven Wrapper  (0) 2022.01.03
[Spring]JobRunr libary 사용  (0) 2021.12.19
[Spring] EJB, POJO 그리고 Spring  (0) 2021.12.12