
Spring Boot 프로젝트에서 spring-boot-starter-data-redis를 사용하여 Redis를 연동하는 방법을 정리합니다. 주요 사용 방식은 RedisTemplate, Spring Cache 추상화, Redis Repositories 세 가지로 나뉩니다.
build.gradle)dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
}
application.yml)src/main/resources/application.yml에 Redis 서버 정보를 설정합니다.
spring:
data:
redis:
host: localhost
port: 6379
# password: your-password # 비밀번호가 설정된 경우
RedisTemplate 사용
Redis의 모든 명령어를 직접 제어할 수 있는 가장 유연한 방식입니다.
RedisTemplate 직렬화 설정
기본 직렬하 방식은 redis-cli로 데이터 확인이 어려워, 일반적으로는 Key는 String, Value는 JSON으로 직렬화하여 사용합니다.
RedisConfig.java
package com.your.project.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
// Key/HashKey 직렬화: StringRedisSerializer 사용
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
// Value/HashValue 직렬화: GenericJackson2JsonRedisSerializer 사용
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
서비스 로직에서 사용
RedisTemplate을 주입받아 데이터 타입에 맞는 Operations를 통해 사용한다.
opsForValue(): StringsopsForList(): ListsopsForHash(): Hashespackage com.your.project.service;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.time.Duration;
@Service
@RequiredArgsConstructor
public class RedisTemplateService {
private final RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public void setWithTTL(String key, Object value, long seconds) {
redisTemplate.opsForValue().set(key, value, Duration.ofSeconds(seconds));
}
}
@Cacheable)메소드의 반환 값을 캐싱하는 어노테이션 기반 방식으로, 코드 변경을 최소화하여 캐싱을 적용할 수 있습니다.
캐싱 활성화
메인 애플리케이션 클래스에 @EnableCaching 어노테이션을 추가합니다.
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class Application {
// ...
}
서비스 메소드에 적용
@Cacheable: 캐시가 있으면 메소드를 실행하지 않고 결과를 반환, 없으면 실행 후 결과를 캐시에 저장@CacheEvict: 캐시를 삭제, 데이터 변경/삭제 시 사용@CachePut: 항상 메소드를 실행하고 결과를 캐시에 갱신package com.your.project.service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
record Product(String id, String name) {}
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product findProductById(String id) {
// DB 조회 로직
System.out.println("Finding product from DB: " + id);
return new Product(id, "Sample Product");
}
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(String id) {
// DB 삭제 로직
System.out.println("Deleting product from DB: " + id);
}
}
JPA와 유사하게 Repository 인터페이스를 정의하여 객체를 Redis의 Hash 구조로 관리하는 방식입니다.
@RedisHash 엔티티 정의
Redis에 저장할 객체 클래스에 @RedisHash를 명시합니다. 키의 prefix로 사용됩니다.
package com.your.project.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
@Getter
@AllArgsConstructor
@RedisHash("people") // "people:[id]" 형태로 키 생성
public class Person {
@Id
private String id;
private String name;
private int age;
}
Repository 인터페이스 정의
CrudRepository를 상속하여 Repository를 생성합니다.
package com.your.project.repository;
import com.your.project.domain.Person;
import org.springframework.data.repository.CrudRepository;
public interface PersonRepository extends CrudRepository<Person, String> {
}
서비스 로직에서 사용
PersonRepository를 주입받아 기본 CRUD 기능을 사용합니다.
package com.your.project.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.your.project.domain.Person;
import com.your.project.repository.PersonRepository;
@Service
@RequiredArgsConstructor
public class PersonService {
private final PersonRepository personRepository;
public Person save(Person person) {
return personRepository.save(person);
}
public Person findById(String id) {
return personRepository.findById(id).orElse(null);
}
}
Spring Boot에서 Redis를 활용하는 세 가지 주요 방식은 다음과 같습니다.
RedisTemplate: Redis의 모든 기능을 유연하게 사용해야 할 때 적합합니다.@Cacheable (Spring Cache) : 기존 코드 수정을 최소화하여 간단하게 캐싱 기능을 도입할 때 가장 효율적입니다.Redis Repositories: 객체를 Redis의 Hash 구조로 관리하는 JPA와 유사한 객체지향적 접근이 필요할 때 유용합니다.프로젝트의 요구사항에 따라 적절한 방식을 선택하여 Redis의 성능 이점을 극대화할 수 있습니다.
좋네요~