在 Gitlab 中将 RabbitMq 作为 GenerigContainer 启动 Ci

Starting RabbitMq as GenerigContainer in Gitlab Ci

我有一个 Spring Boot 2.1 应用程序,它有集成测试。出于集成测试的目的,我想启动一个带有 testcontainers 框架的 RabbitMq 容器。当我在我的本地机器上启动它们时,一切似乎都能正常工作,我可以在 IT 测试期间访问我的 rabbitMQ。但是,一旦我在 gitlab-ci 下执行,我就会不断收到连接被拒绝的异常

这是我的应用程序属性

spring.rabbitmq.host=localhost
spring.rabbitmq.virtualHost=/
spring.rabbitmq.port=5673
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.dynamic=true
spring.rabbitmq.template.retry.enabled=true
spring.rabbitmq.listener.simple.acknowledgeMode=AUTO
spring.rabbitmq.listener.simple.concurrency=5

这是我在gitlab中的验证步骤-ci

verify:feature:
  stage: verify
  script:
    - git config --global user.email gitlab@test.de
    - git config --global user.name gitlab
    - git fetch --all
    - git checkout origin/develop
    - git merge $CI_BUILD_REF --no-commit --no-ff
    - mvn $MAVEN_CLI_OPTS verify sonar:sonar $SONAR_PREVIEW_CLI_OPTS
  only:
    - /feature.*/

这就是我启动测试容器 RabbitMQ 的方式

@Slf4j
@RunWith(SpringRunner.class)
@TestPropertySource(locations = {"classpath:application-it.properties"})
@SpringBootTest
public class TransformerServiceApplicationIt {

  private static final int EXPOSED_RABBITMQ_PORT = 5672;
  private static final int EXPORTED_RABBITMQ_PORT = 5673;

  /**
   * Start the rabbitmq.
   */
  static {
    final Consumer<CreateContainerCmd> rabbitCmd = e -> e.withPortBindings(new PortBinding(Ports.Binding.bindPort(EXPORTED_RABBITMQ_PORT), new ExposedPort(EXPOSED_RABBITMQ_PORT)));
    final GenericContainer rabbitMq = new GenericContainer("rabbitmq:3-management").withExposedPorts(EXPOSED_RABBITMQ_PORT)
        .withCreateContainerCmdModifier(rabbitCmd);
    rabbitMq.start();

  }....
}

这是我的例外

[org.springframework.amqp.rabbit.core.RabbitTemplate]: Factory method 'rabbitTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itRabbitMQConfig': Invocation of init method failed; nested exception is org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused (Connection refused)

我的猜测是它与 gitlab 上 localhost 的主机名解析有关。

试试这个:

  static {
    final GenericContainer rabbitMq = new GenericContainer("rabbitmq:3-management").withExposedPorts(EXPOSED_RABBITMQ_PORT);
    rabbitMq.start();

    // Pass the properties directly to the app. Do not use properties file.
    System.setProperty("spring.rabbitmq.host", rabbitMq.getContainerIpAddress());
    System.setProperty("spring.rabbitmq.port", rabbitMq.getMappedPort(5672).toString());
  }