성능 최적화가 필요한 상황에서 데이터베이스를 자주 조회하지 않고 캐시(Cache)를 사용하면 효과적인 성능 개선이 가능합니다.
Spring Boot에서는 @Cacheable, @CacheEvict, @CachePut 같은 어노테이션 기반 캐시를 매우 손쉽게 사용할 수 있으며, Redis를 백엔드로 연동하면 실무에서도 충분히 활용 가능한 수준의 캐시 시스템을 구성할 수 있습니다.
Redis란 무엇인가?
Redis는 메모리 기반의 키-값 저장소로, 빠른 속도와 다양한 자료구조 지원이 장점입니다.
주로 캐시, 세션 저장소, pub/sub, 분산락 등에 사용됩니다.
Redis 설치 (Docker)
개발환경에서는 Docker로 Redis를 실행하는 게 간편합니다.
docker run --name redis \
-p 6379:6379 \
-d redis:7
build.gradle 또는 pom.xml 의존성 추가
// Gradle 기준
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-cache'
application.yml 설정
spring:
cache:
type: redis
redis:
host: localhost
port: 6379
spring.cache.type을 redis로 설정하면 자동으로 RedisCacheManager가 등록됩니다.
Cache 어노테이션 사용 방법
Spring에서 캐시를 사용하려면 @EnableCaching 어노테이션을 Application 클래스에 선언합니다.
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@Cacheable
결과를 캐시에 저장하고, 같은 파라미터로 다시 호출하면 캐시된 값을 반환합니다.
@Service
public class ProductService {
@Cacheable(value = "product", key = "#id")
public Product findById(Long id) {
simulateSlowQuery(); // DB 호출 시뮬레이션
return productRepository.findById(id).orElseThrow();
}
}
@CacheEvict
캐시를 제거할 때 사용합니다. 주로 업데이트, 삭제 시 활용됩니다.
@CacheEvict(value = "product", key = "#id")
public void deleteProduct(Long id) {
productRepository.deleteById(id);
}
@CachePut
캐시를 강제로 업데이트할 때 사용됩니다.
@CachePut(value = "product", key = "#product.id")
public Product updateProduct(Product product) {
return productRepository.save(product);
}
캐시 TTL 설정하기
기본적으로 Spring Cache는 TTL(Time to Live)을 설정하지 않지만, RedisCacheManager를 커스터마이징하여 TTL을 지정할 수 있습니다.
@Configuration
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)); // 10분 TTL
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.build();
}
}
실무 팁
- 캐시 키는 파라미터가 많을 경우 명확히 지정해야 합니다. (key = "#user.id")
- API 서버가 여러 대일 경우, 외부 Redis 사용이 필수입니다. (내장 캐시는 인스턴스마다 따로 작동)
- 데이터 변경이 잦은 경우에는 짧은 TTL 또는 CacheEvict 사용을 고려하세요.
캐시 저장 확인 (CLI)
Redis CLI를 이용하면 캐시 저장 여부를 직접 확인할 수 있습니다.
redis-cli
> KEYS *
> GET "product::1"
Spring Boot와 Redis는 단 몇 줄의 어노테이션만으로 강력한 캐시 시스템을 구축할 수 있습니다.
특히 읽기 위주의 API에서 큰 성능 향상을 체감할 수 있으며, 실무에서는 Redis TTL 설정, 캐시 키 전략, 통계용 로그 수집 등도 함께 고려하시는 것을 추천드립니다.
'개발 > JAVA' 카테고리의 다른 글
| [JAVA] Spring Boot로 파일 업로드 및 다운로드 API 구현하기 (0) | 2025.10.22 |
|---|---|
| [JAVA] Spring Boot와 Kafka 연동하기 - 실무 개발자를 위한 가이드 (0) | 2025.10.21 |
| [JAVA] Spring Boot와 MongoDB 연동하기 – 실무 중심 입문 가이드 (0) | 2025.10.19 |
| [JAVA] Spring Boot와 PostgreSQL 연동하기 – 실전 가이드 (0) | 2025.10.18 |
| [JAVA] Spring Boot와 MySQL 연동하기 - 입문 가이드 (0) | 2025.10.17 |
