Search code examples
javaspring-bootjunitredis

How to start embedded redis on random available port Java Springboot


@Value("${spring.redis.embedded.port}")

private int redisPort;

private RedisServer redisServer;

@PostConstruct
public void startRedisServer() throws IOException {
    System.out.println("port is "+redisPort);
    redisServer = new RedisServerBuilder()
            .port(redisPort)
           // .setting("bind 0.0.0.0")  // Listen on all network interfaces
            .build();
    redisServer.start();
    System.out.println("redis port is "+redisServer.ports());
}

@PreDestroy
public void stopRedisServer() {
    if (redisServer != null) {
        redisServer.stop();
    }
}

@Bean
public int redisPort() {
    return redisServer.ports().get(0);
}

spring.redis.embedded.port is defined in application-test.properties as 0

This is my code, when I am running it then getting below exception: Caused by: java.lang.RuntimeException: Can't start redis server. Check logs for details. Redis process log: [16480] 24 Jan 10:32:04.901 # Configured to not listen anywhere, exiting. at redis.embedded.AbstractRedisInstance.awaitRedisServerReady(AbstractRedisInstance.java:70) at redis.embedded.AbstractRedisInstance.start(AbstractRedisInstance.java:42) at redis.embedded.RedisServer.start(RedisServer.java:9)


Solution

  • You want to start the embedded Redis on a random available port. Using port = 0 is not an option because this feature is not yet available in embedded Redis.

    As a simple workaround you can use the ServerSocket API as follows:

        int port;
        try (ServerSocket serverSocket = new ServerSocket(0)) {
            assertThat(serverSocket).isNotNull();
            port = serverSocket.getLocalPort();
            System.out.println("ServerSocket port: " + port);
            assertThat(port).isGreaterThan(0);
        } catch (IOException e) {
            fail("Local port not available");
        }
    

    More code examples on getting a free port can be find here:

    https://www.baeldung.com/java-free-port