Embedded Redis Server with Spring Boot Test – 带有Spring Boot测试的嵌入式Redis服务器

最后修改: 2019年 7月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Spring Data Redis provides an easy way to integrate with Redis instances.

Spring Data Redis 提供了一种简单的方法来与Redis实例集成。

However, in some cases, it’s more convenient to use an embedded server than to create an environment with a real server.

然而,在某些情况下,使用嵌入式服务器比用真正的服务器创建一个环境更方便。

Therefore, we’ll learn how to set up and use the Embedded Redis Server.

因此,我们将学习如何设置和使用嵌入式Redis服务器。

2. Dependencies

2.依赖性

Let’s begin by adding the necessary dependencies:

让我们从添加必要的依赖性开始。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
  <groupId>it.ozimov</groupId>
  <artifactId>embedded-redis</artifactId>
  <version>0.7.2</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

The spring-boot-starter-test dependency contains everything we need to run integration tests.

spring-boot-starter-test依赖性包含了我们运行集成测试所需的一切。

Additionally, the embedded-redis contains the embedded server that we’ll use.

此外,embedded-redis包含我们将使用的嵌入式服务器。

3. Setup

3.设置

After adding the dependencies, we should define the connection settings between the Redis server and our application.

添加完依赖关系后,我们应该定义Redis服务器和我们的应用程序之间的连接设置。

Let’s begin by creating a class that will hold our properties:

让我们开始创建一个将容纳我们的属性的类。

@Configuration
public class RedisProperties {
    private int redisPort;
    private String redisHost;

    public RedisProperties(
      @Value("${spring.redis.port}") int redisPort, 
      @Value("${spring.redis.host}") String redisHost) {
        this.redisPort = redisPort;
        this.redisHost = redisHost;
    }

    // getters
}

Next, we should create a configuration class that defines the connection and uses our properties:

接下来,我们应该创建一个配置类,定义连接并使用我们的属性。

@Configuration
@EnableRedisRepositories
public class RedisConfiguration {

    @Bean
    public LettuceConnectionFactory redisConnectionFactory(
      RedisProperties redisProperties) {
        return new LettuceConnectionFactory(
          redisProperties.getRedisHost(), 
          redisProperties.getRedisPort());
    }

    @Bean
    public RedisTemplate<?, ?> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<byte[], byte[]> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        return template;
    }
}

The configuration is quite simple. Additionally, it allows us to run the embedded server on a different port.

该配置相当简单。此外,它允许我们在不同的端口上运行嵌入式服务器。

Check out our Introduction to Spring Data Redis article to learn more about the Redis with Spring Boot.

请查看我们的Spring Data Redis入门文章,以了解更多有关Spring Boot的Redis的信息。

4. Embedded Redis Server

4.嵌入式Redis服务器

Now, we’ll configure the embedded server and use it in one of our tests.

现在,我们将配置嵌入式服务器并在我们的一个测试中使用它。

Firstly, let’s create an application.properties file in the test resource directory (src/test/resources):

首先,让我们在测试资源目录(src/test/resources)中创建一个application.properties文件:

spring.redis.host=localhost
spring.redis.port=6370

After that, we’ll create a @TestConfiguration-annotated class:

之后,我们将创建一个@TestConfiguration注解的类。

@TestConfiguration
public class TestRedisConfiguration {

    private RedisServer redisServer;

    public TestRedisConfiguration(RedisProperties redisProperties) {
        this.redisServer = new RedisServer(redisProperties.getRedisPort());
    }

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

    @PreDestroy
    public void preDestroy() {
        redisServer.stop();
    }
}

The server will start once the context is up. It’ll start on our machine on the port that we’ve defined in our properties. For instance, we can now run the test without stopping the actual Redis server.

一旦上下文建立起来,服务器就会启动。它将在我们的机器上启动,端口是我们在属性中定义的。例如,我们现在可以在不停止实际Redis服务器的情况下运行测试。

Ideally, we’d like to start it on the random available port but embedded Redis doesn’t have this feature yet. What we could do right now is to get the random port via the ServerSocket API.

理想情况下,我们希望在随机的可用端口上启动它,但嵌入式Redis还没有这个功能。我们现在能做的是通过ServerSocket API获得随机端口。

Additionally, the server will stop once the context is destroyed.

此外,一旦上下文被销毁,服务器就会停止。

The server can also be provided with our own executable:

服务器也可以提供我们自己的可执行文件。

this.redisServer = new RedisServer("/path/redis", redisProperties.getRedisPort());

Furthermore, the executable can be defined per operating system:

此外,可执行文件可以按操作系统定义。

RedisExecProvider customProvider = RedisExecProvider.defaultProvider()
  .override(OS.UNIX, "/path/unix/redis")
  .override(OS.Windows, Architecture.x86_64, "/path/windows/redis")
  .override(OS.MAC_OS_X, Architecture.x86_64, "/path/macosx/redis")
  
this.redisServer = new RedisServer(customProvider, redisProperties.getRedisPort());

Finally, let’s create a test that’ll use our TestRedisConfiguration class:

最后,让我们创建一个测试,使用我们的TestRedisConfiguration类。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestRedisConfiguration.class)
public class UserRepositoryIntegrationTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void shouldSaveUser_toRedis() {
        UUID id = UUID.randomUUID();
        User user = new User(id, "name");

        User saved = userRepository.save(user);

        assertNotNull(saved);
    }
}

The user has been saved to our embedded Redis server.

用户已经被保存到我们的嵌入式Redis服务器。

Additionally, we had to manually add TestRedisConfiguration to SpringBootTest. As we said earlier, the server has started before the test and stopped after.

此外,我们不得不手动添加TestRedisConfigurationSpringBootTest。正如我们前面所说,服务器在测试前已经开始,在测试后停止。

5. Conclusion

5.总结

The Embedded Redis Server is the perfect tool to replace the actual server in the test environment. We’ve seen how to configure it and how to use it in our test.

嵌入式Redis服务器是替代测试环境中实际服务器的完美工具。我们已经看到了如何配置它以及如何在我们的测试中使用它。

As always, the code for examples is available over on GitHub.

像往常一样,例子的代码可以在GitHub上找到