Table of Contents
Spring Boot 3.x – Redis
Spring Boot 3.x 에서 Redis 를 사용하는 방법을 정리합니다.
Spring Boot 3.x 가 JDK 17 부터 지원하지만 약간의 소스 수정으로 아래 버전에서도 사용 가능할 것으로 생각합니다.
Spring Boot 2.7.14 에서도 소스코드 수정없이 정상작동합니다.
의존성 추가
dependencies {
// redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.data:spring-data-redis'
}
spring:
data:
redis:
cluster:
nodes: 127.0.0.1:6379
RedisConfig
Entity 를 String 으로 변환해서 저장하는게 가장 간편합니다.
@Configuration
@RequiredArgsConstructor
@EnableRedisRepositories
public class RedisConfig {
private final RedisProperties redisProperties;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(redisProperties.getHost(), redisProperties.getPort());
}
@Bean
public RedisTemplate<?, ?> redisTemplate() {
RedisTemplate<?, ?> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
}
RedisService
ObjectMapper 를 이용해 Json String <-> Entity 간 변환을 수행합니다.
@Service
@RequiredArgsConstructor
public class RedisService {
private final RedisTemplate<String, Object> redisTemplate;
private final ObjectMapper mapper;
public void putData(String key, Object value, Long expiredTime) {
try {
String jsonString = mapper.writeValueAsString(value);
redisTemplate.opsForValue().set(key, jsonString, expiredTime, TimeUnit.MILLISECONDS);
} catch (JsonProcessingException e) {
throw new RuntimeException("Invalid json format: ", e);
}
}
public <T> Optional<T> getData(String key, Class<T> valueType) {
try {
String jsonString = (String) redisTemplate.opsForValue().get(key);
if (StringUtils.hasText(jsonString)) {
return Optional.ofNullable(mapper.readValue(jsonString, valueType));
}
return Optional.empty();
} catch (JsonProcessingException e) {
throw new RuntimeException("Invalid json format: ", e);
}
}
public void remove(String key) {
redisTemplate.delete(key);
}
}
RestController
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MyUserDto {
private String username;
private String password;
private String nickname;
}
@RestController
@RequestMapping("/")
@RequiredArgsConstructor
public class MyController {
private final RedisService redisService;
@GetMapping("/test")
public ResponseEntity<?> test() {
MyUserDto dto = MyUserDto
.builder()
.username("skyer9")
.nickname("상구리")
.build();
redisService.putData("my", dto, 1000L);
Optional<MyUserDto> saved = redisService.getData("my", MyUserDto.class);
return ResponseEntity.ok(saved);
}
}
테스트
브라우저에서 http://localhost:8080/test 로 접속하면 아래 내용이 표시됩니다.
{"username":"skyer9","password":null,"nickname":"상구리"}