I am able to get Spring Boot integration to generate a random free port to launch itself on. But I also need a free port for 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();
}
...
}
Any ideas on how to achieve this?
您可以使用Spring Framework的SocketUtils
来获取可用端口:
int redisPort = SocketUtils.findAvailableTcpPort();
You could also run your Redis within Docker by either using a Java client of your choosing or by leveraging Overcast . If using Overcast, by activating exposeAllPorts
option, your Redis would be bound to a random port on the host machine.
As for how you can enable the property in the context - it would require some work but you could implement a listener that would start up Docker containers and put the ports as properties in an environment:
public class IntegrationTestBootstrapApplicationListener implements
ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 4;
public static final int PROPERTY_SOURCE_NAME = "integrationTestProps";
private int order = DEFAULT_ORDER;
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
if (!environment.getPropertySources().contains(PROPERTY_SOURCE_NAME)) {
CloudHost itestHost = CloudHostFactory.getCloudHost("redis");
itestHost.setup();
String host = itestHost.getHostName();
// fetch the dynamic port from Docker
int port = itestHost.getPort(6379);
// alternatively, skip the whole CloudHost setup above and just use:
// int port = SocketUtils.findAvailableTcpPort();
environment.getPropertySources().addLast(
new MapPropertySource(
PROPERTY_SOURCE_NAME, Collections.<String, Object> singletonMap(
"redis.port", port));
);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.