본문 바로가기

BackEnd/spring

[코프링] coroutine 환경 Cache 적용

반응형

코프링 coroutine 환경에서 캐시 적용하기 위해 삽질을 하여 관련 내용을 기록

기존 spring web mvc와 동일한 방법으로 적용
캐시는 caffeine 적용하기로 하여 관련 종속 추가

    implementation("org.springframework.boot:spring-boot-starter-cache")
    implementation("com.github.ben-manes.caffeine:caffeine")

설정 추가

@Configuration
@EnableCaching
class CacheConfig {
    @Bean
    fun cacheManager(): CacheManager {
        val caches: List<CaffeineCache> = Arrays.stream(CacheType.values())
            .map { cache ->
                CaffeineCache(
                    cache.getCacheName(), Caffeine.newBuilder().recordStats()
                        .expireAfterWrite(cache.getExpiredAfterWrite(), TimeUnit.MINUTES)
                        .maximumSize(cache.getMaximumSize())
                        .build()
                )
            }
            .collect(Collectors.toList())
        val cacheManager = SimpleCacheManager()
        cacheManager.setCaches(caches)
        return cacheManager
    }
}

캐시관리용 enum 추가

enum class CacheType(private val cacheName: String, private val expiredAfterWrite: Long, private val maximumSize: Long) {
    TEST_1(Constants.TEST_1, Constants.CACHE_TTL_1D, 10000),

    fun getCacheName(): String = cacheName
    fun getExpiredAfterWrite(): Long = expiredAfterWrite
    fun getMaximumSize(): Long = maximumSize
}


service 캐시 적용

 @Cacheable(cacheNames = [Constants.TEST_1])
    suspend fun getChannelPolicy(): List<ChannelDto.Value> {        
        val response = channelClient.getChannelInfo()      
        return response
    }

Test시 캐시가 적용되지 않고 계속 외부 API를 호출 하였다

많은 구글링후 적용하여봤으나 제대로 되지 않았고
아래 참고문서를 참고하여 적용



추가 적용한 소스
1. 종속성 추가

implementation("org.springframework.kotlin:spring-kotlin-coroutine:0.3.7")


2. 설정 Annotation 추가 (@EnableCoroutine)

@Configuration
@EnableCaching
@EnableCoroutine
class CacheConfig {

3. Test
캐시 적용이 잘되며 expire도 설정한 시간대로 잘 적용되었다.


[참고문서] : https://github.com/konrad-kaminski/spring-kotlin-coroutine/blob/master/README.md

 

GitHub - konrad-kaminski/spring-kotlin-coroutine: Kotlin coroutine support for Spring.

Kotlin coroutine support for Spring. Contribute to konrad-kaminski/spring-kotlin-coroutine development by creating an account on GitHub.

github.com

 

반응형