아무거나

Kotlin + Spring Boot 에 Ehcache 적용 본문

Java & Kotlin/Kotlin

Kotlin + Spring Boot 에 Ehcache 적용

전봉근 2024. 5. 30. 15:35
반응형

EhCache 적용

  1. 의존성 추가(build.gradle.kts)
...

dependencies {
  ...

	// Cache
	implementation("org.springframework.boot:spring-boot-starter-cache")
	implementation("org.ehcache:ehcache:3.9.5")  

...
  1. Application 구동 클래스에 @EnableCaching 추가
@EnableCaching  // 추가
@SpringBootApplication
class KotlinJpaCodebaseApplication

fun main(args: Array<String>) {
	runApplication<KotlinJpaCodebaseApplication>(*args)
}
  1. Config 관련 클래스 추가
    [EhCacheConfig.kt]
@Configuration
class EhCacheConfig {
  ...
}

[EhCacheLogger.kt]

import com.bkjeon.base.core.log.logger
import org.ehcache.event.CacheEvent
import org.ehcache.event.CacheEventListener

class EhCacheLogger: CacheEventListener<Any, Any> {

    private val log = logger()

    override fun onEvent(cacheEvent: CacheEvent<out Any, out Any>) {
        log.info("Key: [${cacheEvent.key}] | EventType: [${cacheEvent.type}] | Old value: [${cacheEvent.oldValue}] | New value: [${cacheEvent.newValue}]")
    }

}
  1. Cache 적용
    [resources/ehcache.xml]
<config
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>
    <cache-template name="default">
        <listeners>
            <listener>
                <class>com.bkjeon.base.core.config.cache.EhCacheLogger</class>
                <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                <event-ordering-mode>UNORDERED</event-ordering-mode>
                <events-to-fire-on>CREATED</events-to-fire-on>
                <events-to-fire-on>UPDATED</events-to-fire-on>
                <events-to-fire-on>EXPIRED</events-to-fire-on>
                <events-to-fire-on>REMOVED</events-to-fire-on>
                <events-to-fire-on>EVICTED</events-to-fire-on>
            </listener>
        </listeners>
    </cache-template>

    <cache alias="getCacheSampleList" uses-template="default">
        <key-type>java.lang.String</key-type>
        <value-type>java.util.ArrayList</value-type>
        <expiry>
            <ttl unit="minutes">60</ttl>
        </expiry>
        <resources>
            <heap>100</heap>
            <offheap unit="MB">1</offheap>
        </resources>
    </cache>
</config>

[CacheSampleService.kt]

@Cacheable(cacheNames = ["getCacheSampleList"])
fun getCacheSampleList(@ModelAttribute request: CacheSampleRequest): String {
    log.info("EhCache Key List: ${cacheManager.cacheNames}")

    val sampleDataList: MutableList<SampleData> = ArrayList()
    for (i: Int in 1..10000000) {
        sampleDataList.add(SampleData("bkjeon", i, 20_000))
    }
    for (i: Int in 1..10000000) {
        sampleDataList.add(SampleData("bkjeon2", i, 20_000))
    }

    return "OK"
}
  1. Event 로깅 추가
    [application.yml]
...

logging:
  level:
    org.springframework.cache: TRACE
반응형
Comments