我能够让Spring Boot集成自动生成一个随机的空闲端口来启动自身。但是我也需要为Redis获得一个空闲端口。
@ContextConfiguration(classes = {MyApplication.class}, loader = SpringApplicationContextLoader.class)
@WebIntegrationTest(randomPort = true, value = "server.port:0")
@ActiveProfiles(profiles = {"local"})
public class SegmentSteps {
private static final String HOST_TEMPLATE = "http://localhost:%s";
// Needs to be a random open port
private static final int REDIS_PORT = 6380;
private String host;
@Value("${local.server.port}")
private int serverPort;
private RedisServer redisServer;
@Before
public void beforeScenario() throws Exception {
host = String.format(HOST_TEMPLATE, serverPort);
redisServer = RedisServer.builder()
.redisExecProvider(RedisExecProvider.defaultProvider())
.port(REDIS_PORT)
.setting("bind 127.0.0.1")
.build();
redisServer.start();
}
...
}
如何实现这一目标呢?
SocketUtils
已经被弃用,自 Spring Framework 5.3.16 开始,将在 6.0 版本中移除。 - Andrei Damian-Feketeorg.springframework.test.util.TestSocketUtils.findAvailableTcpPort()
。 - Udo Klimaschewski