【问题标题】:Spring Boot cloud GCP cannot connect to local Google PubSub emulatorSpring Boot cloud GCP 无法连接到本地 Google PubSub 模拟器
【发布时间】:2018-07-11 16:11:33
【问题描述】:

尝试从 Spring 启动应用程序连接到本地 Google PubSub 模拟器进行测试。

使用下面的配置
spring.cloud.gcp.pubsub.emulator-host=localhost:8085

在 8085 本地成功启动模拟器,也设置了 PUBSUB_EMULATOR_HOST=localhost:8085

注意:在连接到实际的 Google PubSub 主题时,一切正常。

【问题讨论】:

    标签: spring-boot google-cloud-pubsub


    【解决方案1】:
    1. src/test/resources/application.properties下创建文件
    2. 在测试应用程序.properties 中设置spring.cloud.gcp.pubsub.emulator-host=localhost:8085
    3. 注释您的测试类,以便 Spring 选择您的测试 application.properties:
    @RunWith(SpringRunner::class)
    @SpringBootTest
    

    编辑:我创建了一个示例项目,展示了如何在测试中使用 Spring 和 PubSub 模拟器(还需要创建主题和订阅):https://github.com/nhartner/pubsub-emulator-demo

    【讨论】:

      【解决方案2】:

      使用 Pub/Sub 模拟器时,使用 FixedTransportChannelProviderNoCredentialsProvider 创建 PublisherSubscriber。这在UsePubSubEmulatorSnippet.java 中得到了证明:

      String hostport = System.getenv("PUBSUB_EMULATOR_HOST");
      ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext(true).build();
      TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
      
      CredentialsProvider credentialsProvider = NoCredentialsProvider.create();
      
      ProjectTopicName topicName = ...
      
      // Use the channel and credentials provider when creating a Publisher or Subscriber.
      Publisher publisher =
          Publisher.newBuilder(topicName)
              .setChannelProvider(channelProvider)
              .setCredentialsProvider(credentialsProvider)
              .build();
      

      【讨论】:

        【解决方案3】:

        我们可以使用Testcontainers 方法来使用所有支持的服务。它为您提供了一个 docker 容器,模拟器将在其中运行,并帮助您为多个项目使用不同的配置,并根据单个测试用例更新测试设置。对于 pubsub,请使用以下配置创建初始设置:即主题和订阅

        companion object {
            private val log = logger(GCPSetup::class.java)
            private val emulator: PubSubEmulatorContainer = PubSubEmulatorContainer(
                DockerImageName.parse("gcr.io/google.com/cloudsdktool/cloud-sdk:316.0.0-emulators")
            )
        
            init {
                emulator.start()
            }
        
            @Configuration
            class EmulatorConfiguration{
                @Bean
                fun credentialProvider() = NoCredentialsProvider()
            }
            @DynamicPropertySource
            fun emulatorProperties(registry:DynamicPropertyRegistry){
                registry.add("spring.cloud.gcp.pubsub.emulator-host") { emulator.emulatorEndpoint }
            }
        }
        

        上面的例子是在Kotlin中,但是你可以在java的静态块中使用上面的配置。

        【讨论】:

          猜你喜欢
          • 2020-11-28
          • 2018-12-15
          • 2021-03-15
          • 2020-03-27
          • 2020-08-18
          • 1970-01-01
          • 2020-04-22
          • 2019-11-27
          • 1970-01-01
          相关资源
          最近更新 更多