首页 > 解决方案 > Google Pub/Sub 主题创建

问题描述

我正在尝试在我的机器上使用 google pub sub 模拟器来创建主题。

但是当我尝试执行创建主题的代码时,我得到一个TestTimedOutException.
我正在尝试执行 google 在其文档页面上提供的步骤/代码。

这是我的代码:

public static void main(String args[] ){
   //project id
   String projectId = ServiceOptions.getDefaultProjectId();
   //topic id
   String topicId = args[0];

    // Create a new topic
    ProjectTopicName topic = ProjectTopicName.of(projectId, topicId);
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
          System.out.println("Topics");
          topicAdminClient.createTopic(topic);
          System.out.printf("Topic %s:%s created.\n", topic.getProject(),                           
                                topic.getTopic());
    } catch(ApiException e) {
       System.out.println(e.getStatusCode().getCode());
       System.out.println(e.isRetryable());
    }
}

运行示例时出错:

[INFO] Running com.example.pubsub.QuickStartIT
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 301.26 s <<< FAILURE! - in com.example.pubsub.QuickStartIT
[ERROR] testQuickstart(com.example.pubsub.QuickStartIT)  Time elapsed: 301.153 s  <<< ERROR!
org.junit.runners.model.TestTimedOutException: test timed out after 300 seconds  
        at com.example.pubsub.QuickStartIT.deleteTestSubscription(QuickStartIT.java:144)  
        at com.example.pubsub.QuickStartIT.setUp(QuickStartIT.java:80)

标签: javagoogle-cloud-pubsub

解决方案


您所指的示例,它被配置为直接在 Google Cloud 上运行。为了使示例在您的本地 Pub/Sub 模拟器上运行,您必须在代码中指定它应该连接到您的模拟器主机。

主机端口应添加到您的代码中:

String hostport = System.getenv("PUBSUB_EMULATOR_HOST");
ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext().build();
try {
  TransportChannelProvider channelProvider =
      FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
  CredentialsProvider credentialsProvider = NoCredentialsProvider.create();

  // Set the channel and credentials provider when creating a `TopicAdminClient`.
  // Similarly for SubscriptionAdminClient
  TopicAdminClient topicClient =
      TopicAdminClient.create(
          TopicAdminSettings.newBuilder()
              .setTransportChannelProvider(channelProvider)
              .setCredentialsProvider(credentialsProvider)
              .build());

  ProjectTopicName topicName = ProjectTopicName.of("my-project-id", "my-topic-id");
  // Set the channel and credentials provider when creating a `Publisher`.
  // Similarly for Subscriber
  Publisher publisher =
      Publisher.newBuilder(topicName)
          .setChannelProvider(channelProvider)
          .setCredentialsProvider(credentialsProvider)
          .build();
} finally {
  channel.shutdown();
}

您可以在公共文档中找到有关如何正确设置环境以使用本地 Pub/Sub 模拟器的更多信息。


推荐阅读