Tutorial on using embedded redis server in spring boot test

Time:2022-6-19

1. Overview

Spring Data RedisProvides a simple method for integrating with redis instances.

However, in some cases, using an embedded server is more convenient than using a real server to create a development and test environment.

Therefore, we will learn how to set up and use the embedded redis server.

2. Dependency

Let’s first add 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>

thisspring-boot-starter-testContains various dependencies that we need to run integration tests.

In addition,embedded-redisContains the embedded server we will use.

3. Settings

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

Let’s first create a class to 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 to define the connection and use 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 very simple. In this way, our embedded server can run on other ports.

4. Embedded redis server

Now we will configure the embedded server and use it in one of our tests.

First, let’s create an application Properties file:


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

After that, we will create a configuration class annotated with @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();
    }
}

When the context is started, the server will start. It runs on our machine according to the port we defined in the properties. With it, we can now run the test without stopping the actual redis server.

Ideally, we want to start it on the random available port, but embedded redis does not yet have this function. What we can do now is to obtain random ports through the ServerSocket API.

In addition, when the context stops, the server also stops.

The server can also be provided by our own executable file:


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

In addition, executable files can be defined according to different operating systems:


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 using the testredisconfiguration class:


@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);
    }
}

In this way, users can save to our embedded redis server.

In addition, we have to manuallyTestRedisConfigurationAdd toSpringBootTest。 As we said earlier, the server starts before the test and stops after the test.

5. Conclusion

The embedded redis server is a perfect tool to replace the actual server in the test environment. We have seen how to configure it and how to use it in our tests.

This is the end of this article about the use of embedded redis servers in spring boot testing. For more information about the use of redis spring boot, please search the previous articles of developeppaer or continue to browse the following articles. I hope you will support developeppaer in the future!

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]