gpt4 book ai didi

postgresql - 使用 Testcontainers 时如何设置 Postgresql 的端口?

转载 作者:行者123 更新时间:2023-12-05 01:57:34 26 4
gpt4 key购买 nike

有时我需要为 Postgresql 安装一个端口,我在容器中运行它以进行测试。但是Test容器的开发者命令Testcontainers去掉了这个特性。但是在某个地方有一个解决方法,通过设置,但我找不到它。谁有关于如何执行此操作的任何想法或信息?

public class ContainerConfig {

private static final PostgreSQLContainer postgresSQLContainer;

static {
DockerImageName postgres = DockerImageName.parse("postgres:13.1");

postgresSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer(postgres)
.withDatabaseName("test")
.withUsername("root")
.withPassword("root")
.withReuse(true);

postgresSQLContainer.start();
}

@SuppressWarnings("rawtypes")
private static PostgreSQLContainer getPostgresSQLContainer() {
return postgresSQLContainer;
}


@SuppressWarnings("unused")
@DynamicPropertySource
public static void registerPgProperties(DynamicPropertyRegistry propertyRegistry) {

propertyRegistry.add("integration-tests-db", getPostgresSQLContainer()::getDatabaseName);
propertyRegistry.add("spring.datasource.username", getPostgresSQLContainer()::getUsername);
propertyRegistry.add("spring.datasource.password", getPostgresSQLContainer()::getPassword);
propertyRegistry.add("spring.datasource.url", getPostgresSQLContainer()::getJdbcUrl);
}

}

最佳答案

使用 withCreateContainerCmdModifier 添加端口绑定(bind)。

static {
int containerPort = 5432 ;
int localPort = 5432 ;
DockerImageName postgres = DockerImageName.parse("postgres:13.1");
postgreDBContainer = new PostgreSQLContainer<>(postgres)
.withDatabaseName("test")
.withUsername("root")
.withPassword("root")
.withReuse(true)
.withExposedPorts(containerPort)
.withCreateContainerCmdModifier(cmd -> cmd.withHostConfig(
new HostConfig().withPortBindings(new PortBinding(Ports.Binding.bindPort(localPort), new ExposedPort(containerPort)))
));
postgreDBContainer.start();
}

关于postgresql - 使用 Testcontainers 时如何设置 Postgresql 的端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69132686/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com