spring-boot-cache은(는) 무엇을 하나요?
Spring Boot 캐싱 구현을 위한 패턴을 제공합니다: Redis/Caffeine/EhCache 프로바이더를 TTL 및 제거 정책과 함께 구성하고, @Cacheable/@CacheEvict/@CachePut 어노테이션을 적용하며, 캐시 적중/실패 동작을 검증하고, Actuator를 통해 메트릭을 노출합니다. Spring Boot 서비스에 캐싱을 추가하거나, 캐시 만료를 구성하거나, 오래된 데이터를 제거하거나, 캐시 미스를 진단할 때 사용하세요.
캐시 프로바이더 구성
application.yml 또는 application.properties에 캐시 프로바이더를 구성합니다.
Redis
spring:
cache:
type: redis
redis:
host: localhost
port: 6379
Caffeine
spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterWrite=10m
EhCache
ehcache.xml 파일 생성:
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3'
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd">
<cache alias="items">
<expiry>
<ttl unit="minutes">10</ttl>
</expiry>
<resources>
<heap unit="entries">500</heap>
</resources>
</cache>
</config>
spring:
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
캐시 어노테이션 적용
@Cacheable
@Service
public class ItemService {
@Cacheable(value = "items", key = "#id")
public Item getItemById(Long id) {
// 느린 데이터베이스 호출
return itemRepository.findById(id).orElseThrow();
}
}
@CacheEvict
@CacheEvict(value = "items", allEntries = true)
public void refreshItems() {
// 모든 항목 다시 로드
}
@CachePut
@CachePut(value = "items", key = "#item.id")
public Item updateItem(Item item) {
return itemRepository.save(item);
}
캐시 활성화
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("items");
}
}
검증
캐시 동작을 검증하는 테스트:
@SpringBootTest
@AutoConfigureMockMvc
class CacheTest {
@Autowired
private ItemService itemService;
@Test
void testCacheHit() {
itemService.getItemById(1L); // 첫 번째 호출 - 캐시 미스
itemService.getItemById(1L); // 두 번째 호출 - 캐시 적중
}
}
Actuator 메트릭
application.yml에서 Actuator 캐시 메트릭 활성화:
management:
endpoints:
web:
exposure:
include: health,info,cache,metrics
metrics:
cache:
enabled: true
캐시 메트릭 확인:
curl http://localhost:8080/actuator/cache
curl http://localhost:8080/actuator/metrics/cache.gets