Redis ‐ Embedded Redis Server with Spring Boot Test - thought-corner/Backend-PlayGround GitHub Wiki

Redis - Embedded Redis Server with Spring Boot Test

  • Embedded Redis는 Redis 서버를 별도로 필요로 하지 않고 애플리케이션 내부에서 직접 Redis 서버가 동작되는 환경을 말한다.
  • 회사 프로젝트에서 데이터를 레디스에 캐싱해서 사용하는 부분에서 테스트 검증이 필요했고 그 과정에서 TestContainer와 Embedded Redis를 고민했고 쉽게 테스트 환경을 구축하고자 Embedded Redis를 사용하게 되었다.
  • Embedded Redis가 테스트 환경에서 사용될 수 있는 이유는 다음과 같다.
    • 테스트마다 독립적인 Redis 환경을 구축하여 테스트 간 종속성을 줄일 수 있다.
    • 실제 Redis 서버와의 연결없이 테스트를 할 수 있다.
    • 배포 파이프라인 동작을 수행할 때 네트워크에 대해 고민하지 않도록 해준다.
@TestConfiguration
public class TestEmbeddedRedisConfiguration {

    private final RedisServer redisServer;

    public TestEmbeddedRedisConfiguration(TestRedisProperties properties) throws IOException {
        this.redisServer = new RedisServer(properties.getPort());
    }

    @PostConstruct
    public void postConstruct() throws IOException {
        redisServer.start();
    }

    @PreDestroy
    public void preDestroy() throws IOException {
        redisServer.stop();
    }
}
@TestConfiguration
@RequiredArgsConstructor
@EnableConfigurationProperties(TestRedisProperties.class)
public class TestRedisConfiguration {

    @Bean
    public LettuceConnectionFactory testRedisConnectionFactory(TestRedisProperties properties) {
        return new LettuceConnectionFactory(properties.getHost(), properties.getPort());
    }

    @Bean
    public RedisTemplate<String, Object> testRedisTemplate(LettuceConnectionFactory testRedisConnectionFactory) {
        final RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(testRedisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJacksonJsonRedisSerializer(new ObjectMapper()));
        return template;
    }

}
@Data
@ConfigurationProperties(prefix = "spring.data.redis")
public class TestRedisProperties {

    private int port;
    private String host;
}