반응형
Redis는 인메모리 데이터 저장소로서, 빠른 속도를 활용해 캐싱, 세션 관리, 메시지 큐 등 다양한 용도로 사용됩니다. Spring Boot와 함께 사용하면 애플리케이션의 성능을 크게 향상시킬 수 있습니다.
Redis 캐싱의 장점
- 고속 데이터 처리 - 메모리 기반 저장 방식으로 빠른 속도 제공
- 데이터 지속성 - 스냅샷(Snapshot) 및 AOF(Append-Only File) 기능 지원
- 세션 관리 - 웹 애플리케이션의 사용자 세션을 효율적으로 저장
- 분산 시스템 지원 - 여러 개의 노드로 확장 가능
Redis 설치 및 설정
Redis를 설치한 후, 기본 설정을 변경합니다.
# Redis 서버 실행 (리눅스)
sudo apt update
sudo apt install redis-server
sudo systemctl start redis
# Redis 설정 파일 수정 (/etc/redis/redis.conf)
maxmemory 256mb
maxmemory-policy allkeys-lru
Spring Boot 프로젝트에서 Redis 설정
Spring Boot 프로젝트에서 Redis를 사용하려면, spring-boot-starter-data-redis
의존성을 추가합니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Redis 연결 설정
Redis 서버와 연결하기 위한 application.properties
설정을 추가합니다.
spring.redis.host=localhost
spring.redis.port=6379
Redis 캐싱을 위한 설정 클래스
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // 캐시 만료 시간 설정
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(config)
.build();
}
}
Redis를 활용한 캐싱 적용
아래는 Spring Boot에서 Redis 캐싱을 적용한 예제입니다.
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public String getProductById(String id) {
try {
Thread.sleep(3000); // 데이터베이스 호출을 가정한 지연 시간
} catch (InterruptedException e) {
e.printStackTrace();
}
return "상품 정보: " + id;
}
}
Redis 캐싱 테스트
이제 컨트롤러를 만들어 Redis 캐싱이 잘 동작하는지 확인합니다.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/product")
public String getProduct(@RequestParam String id) {
return productService.getProductById(id);
}
}
Redis 캐싱 확인 방법
애플리케이션을 실행한 후, 두 번째 요청이 훨씬 빠르게 실행되는지 확인하세요.
- 첫 번째 요청:
GET http://localhost:8080/product?id=123
(약 3초 소요) - 두 번째 요청:
GET http://localhost:8080/product?id=123
(즉시 응답)
Redis 캐싱 학습 추천 자료
- 📌 Spring Boot + Redis 강의 (인프런, 유튜브)
마무리
Spring Boot와 Redis를 활용하면 애플리케이션의 성능을 크게 향상시킬 수 있습니다. 특히 데이터베이스 부하를 줄이면서도 빠른 응답을 제공할 수 있어 실무에서 널리 사용됩니다.
반응형