[Spring Boot] Spring Cache

Spring Boot

(Update : 2023-02-18)

Language :

Provides cache abstraction.

  • Set the cache to Bean using Spring-oriented programming (AOP).
  • Because it is not dependent on specific cache technologies, it minimizes the impact on code and allows for consistent use of various cache solutions.

Basically, it uses a Map store created based on Concurrent HashMap.

There are Annotation-based caching and XML-based caching.

Cache Manager

ConcurrentMapCacheManager: A simple cache manager that stores cache information in ConcurrentHashMap.Due to its low functionality, actual service use is not recommended.

SimpleCacheManager: Cache manager without cache provided by default.You must register the cache directly for use with setCache.

EhCacheCacheManager: Cache Manager with the Cache Framework Ehcache

CompositeCacheManager: A composite cache manager that allows multiple cache managers to be used

JCacheCacheManager: Cache Manager with JSR-107 based cache

Add Dependencies

xml

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-cache")
}

Enable cache function

Method 1. Enable the default Spring Cache feature

kotlin

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

@SpringBootApplication
@EnableCaching
class DevApplication

Method 2. Setting Up Subdirty Module Cache Usage

kotlin

@Configuration
@EnableCaching
class CacheConfig {

    @Bean
    fun cacheManager(): CacheManager {
        val manager = SimpleCacheManager()
        manager.setCaches(
            listOf(
                ConcurrentMapCache("cacheStore1"),
                ConcurrentMapCache("cacheStore2")
            )
        )
        return manager
    }

}

Annotation-based caching

@Cacheable

Saves the method result to the cache.If there is cache data, it returns cached results without performing method internal logic.

kotlin

package org.springframework.cache.annotation;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Cacheable

Default use. Declares above method by specifying cache name.

kotlin

@Cacheable("cacheStore")
fun findComment(userId: Long): Comment

If the factor is Entity, you must specify a key value to cache.

kotlin

@Cacheable(cacheNames = ["cacheStore"], key = "#user.id")
fun findComment(user: User): Comment

Key cannot be duplicated in the same cache.The code below causes an error.

kotlin

@Cacheable(cacheNames = ["cacheStore"], key = "#user.id")
fun findComment1(user: User): Comment

@Cacheable(cacheNames = ["cacheStore"], key = "#user.id")
fun findComment2(user: User): Comment

@CachePut

Refresh Cache

@Not recommended for use with Cacheable.

kotlin

@CachePut(cacheNames = ["cacheStore"], key = "#user.id")
fun updateComment(user: User): Comment

@CacheEvict

Remove Cache

It is used to prevent the cached data source from being changed and deleted separately from the cache life cycle, thereby breaking the consistency.

Available for methods with no return value

kotlin

@CacheEvict(cacheNames = ["cacheStore"], key = "#user.id")
fun loadComment(user: User)

@Caching

Used when multiple of the same types need to be attached.

kotlin

@Caching(cacheable = [Cacheable("store1"), Cacheable(cacheNames = ["store2"], key = "#p0")])
fun method1(id: Long, date: LocalDate)

@Caching(put = [CachePut("store1"), CachePut(cacheNames = ["store2"], key = "#p0")])
fun method2(id: Long, date: LocalDate)

@Caching(evict = [CacheEvict("store1"), CacheEvict(cacheNames = ["store2"], key = "#p0")])
fun method3(id: Long, date: LocalDate)

@CacheConfig

Specifies the cache name at the single class level.

kotlin

@CacheConfig(cacheNames = ["cacheStore"])
class CommentRepositoryImpl : CommentRepository {
    @Cacheable(key = "#user.id")
    fun findComment(user: User): Comment
}

ERROR

text

Exception in thread "http-nio-8082-exec-3" java.lang.NoClassDefFoundError: ch/qos/logback/classic/spi/ThrowableProxy

Occurs hepatic during Docker restart
Guess it's an error that occurs when you look for cache missing and it exists
Need to check if adding spring-boot-starter-logging or logback-classic dependencies solves it

Reference

Integration

Spring Cache Abstracting Basic Usage @Cacheable @CachePut @CacheEvict

Let's apply capeine cache to Spring boot - how can I not work?

Attempt to improve project performance with cache on spring - Jinia's LOG'

Spring in action - 13. Caching data

About Cache...(Spring+EHCache) Carrey's Technical Blog

Spring Cache, working properly

Introducing Spring Boot Caching (Redis, Ehcache)

민갤

Back-End Developer

백엔드 개발자입니다.