Обёртка для testcontainers RabbitMQ + spring-multirabbit. Умеет писать в контейнер.
import lombok.Getter;
import lombok.SneakyThrows;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.testcontainers.containers.Container.ExecResult;
import org.testcontainers.containers.RabbitMQContainer;
import org.testcontainers.utility.DockerImageName;
public class RabbitMqContainerWrapper {
// https://www.rabbitmq.com/management-cli.html
private static final String IMAGE = "rabbitmq:management";
private final boolean reserve;
@Getter
private final String queueName;
@Getter
private final RabbitMQContainer container;
public RabbitMqContainerWrapper(String queueName, boolean reserve) {
this.queueName = queueName;
this.reserve = reserve;
container = new RabbitMQContainer(
DockerImageName.parse(IMAGE).asCompatibleSubstituteFor("rabbitmq")
);
initContainer();
}
public RabbitMqContainerWrapper() {
this("default_queue", false);
}
@SneakyThrows
public ExecResult publishMessage(String message) {
return container.execInContainer(
"rabbitmqadmin", "publish", "exchange=amq.default",
"routing_key=%s".formatted(queueName),
"payload=%s".formatted(message)
);
}
@SneakyThrows
public void initContainer() {
container.start();
container.execInContainer(
"rabbitmqadmin", "declare", "queue", "durable=true", "name=%s".formatted(queueName)
);
}
public void initProperties(DynamicPropertyRegistry registry) {
registry.add("amqp.queue.name", this::getQueueName);
if (!reserve) {
registry.add("spring.rabbitmq.host", container::getHost);
registry.add("spring.rabbitmq.port", container::getAmqpPort);
registry.add("spring.rabbitmq.username", container::getAdminUsername);
registry.add("spring.rabbitmq.password", container::getAdminPassword);
} else {
registry.add("spring.multirabbitmq.connections.reserve-cluster.host", container::getHost);
registry.add("spring.multirabbitmq.connections.reserve-cluster.port", container::getAmqpPort);
registry.add("spring.multirabbitmq.connections.reserve-cluster.username", container::getAdminUsername);
registry.add("spring.multirabbitmq.connections.reserve-cluster.password", container::getAdminPassword);
}
}
}