Google Pub / Sub主题创建

时间:2019-08-30 19:43:42

标签: java google-cloud-pubsub

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

但是当我尝试执行创建主题的代码时,会得到TestTimedOutException
我正在尝试执行Google在其documentation page上提供的步骤/代码。

这是我的代码:

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)

1 个答案:

答案 0 :(得分:0)

您要参考的示例已配置为直接在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();
}

您可以在public documentation中找到有关如何正确设置环境以与本地发布/订阅模拟器一起使用的更多信息。