728x90
1. 로컬 캐시란?
- 서버 내부 메모리(Heap) 에 데이터를 캐싱하는 방식.
- 대표적으로 Caffeine, Guava, EhCache 같은 라이브러리를 사용.
- 장점
1) 낮은 지연 시간: DB나 Redis까지 가지 않고 바로 응답
2) 구현 단순: 라이브러리 import 후 간단하게 적용 가능
3) 추가 비용 없음: 별도 캐시 서버 필요 없음
2. 스프링 캐시는?
1) 추상화된 공통 API 제공
- @Cacheable, @CachePut, @CacheEvict, @Caching 같은 어노테이션을 제공
- 개발자는 캐시 라이브러리(Caffeine, Redis, Ehcache 등)를 몰라도 동일한 방식으로 사용 가능
2) 다양한 캐시 구현체 연동
- Caffeine (로컬)
- Ehcache (로컬 + 디스크)
- Redis (분산 캐시)
- Hazelcast / Infinispan (분산 인메모리 캐시)
//Spring Boot Auto Configuration 덕분에 의존성만 추가하면 자동으로 연결됨.
"Spring 캐시 + Caffeine 조합으로 로컬 캐시을 적용해보자"
3. 설정 방법
1) 의존성 추가
// build.gradle.kts
dependencies {
implementation("org.springframework.boot:spring-boot-starter-cache")
implementation("cohttp://m.github.ben-manes.caffeine:caffeine:3.1.8")
}
2) config 추가
import com.github.benmanes.caffeine.cache.Caffeine
import org.springframework.cache.CacheManager
import org.springframework.cache.annotation.EnableCaching
import org.springframework.cache.caffeine.CaffeineCacheManager
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.concurrent.TimeUnit
@Configuration
@EnableCaching
class CacheConfig {
@Bean
fun caffeineConfig(): Caffeine<Any, Any> =
Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES) // 10분 뒤 만료
.maximumSize(1000) // 최대 1000개 키 저장
@Bean
fun cacheManager(caffeine: Caffeine<Any, Any>): CacheManager {
val cacheManager = CaffeineCacheManager()
cacheManager.setCaffeine(caffeine)
return cacheManager
}
}
3) 사용예시
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
@Service
class UserService {
@Cacheable(cacheNames = ["user"], key = "#userId")
fun getUser(userId: Long): String {
println("DB 조회 발생: $userId")
return "User-$userId"
}
}
4. HomeBody 상품 리스트 구현 내 로컬 캐싱 추가
ㅇ
728x90
'Kotlin Spring > Kotlin Spring 강의 내용' 카테고리의 다른 글
8) Spring 캐시 (3)redis란? (0) | 2025.09.05 |
---|---|
8) Spring 캐시 (2)분산 캐시란? (0) | 2025.09.02 |
7) 주요 기능 개발(Back-end) (0) | 2025.09.02 |
6) 개발 architecture (5) 강의용 Architecture (0) | 2025.09.01 |
6) 개발 architecture (4) EDA(Event-Driven Architecture) 패턴 (1) | 2025.08.31 |