当前位置: 首页>>代码示例>>Java>>正文


Java Publisher.shutdown方法代码示例

本文整理汇总了Java中com.google.cloud.pubsub.v1.Publisher.shutdown方法的典型用法代码示例。如果您正苦于以下问题:Java Publisher.shutdown方法的具体用法?Java Publisher.shutdown怎么用?Java Publisher.shutdown使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.google.cloud.pubsub.v1.Publisher的用法示例。


在下文中一共展示了Publisher.shutdown方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import com.google.cloud.pubsub.v1.Publisher; //导入方法依赖的package包/类
/** Publish messages to a topic.
 * @param args topic name, number of messages
 */
public static void main(String... args) throws Exception {
  // topic id, eg. "my-topic"
  String topicId = args[0];
  int messageCount = Integer.parseInt(args[1]);
  TopicName topicName = TopicName.of(PROJECT_ID, topicId);
  Publisher publisher = null;
  try {
    // Create a publisher instance with default settings bound to the topic
    publisher = Publisher.newBuilder(topicName).build();

    for (int i = 0; i < messageCount; i++) {
      String message = "message-" + i;

      // convert message to bytes
      ByteString data = ByteString.copyFromUtf8(message);
      PubsubMessage pubsubMessage = PubsubMessage.newBuilder()
          .setData(data)
          .build();

      //schedule a message to be published, messages are automatically batched
      ApiFuture<String> future = publisher.publish(pubsubMessage);

      // add an asynchronous callback to handle success / failure
      ApiFutures.addCallback(future, new ApiFutureCallback<String>() {

        @Override
        public void onFailure(Throwable throwable) {
          if (throwable instanceof ApiException) {
            ApiException apiException = ((ApiException) throwable);
            // details on the API exception
            System.out.println(apiException.getStatusCode().getCode());
            System.out.println(apiException.isRetryable());
          }
          System.out.println("Error publishing message : " + message);
        }

        @Override
        public void onSuccess(String messageId) {
          // Once published, returns server-assigned message ids (unique within the topic)
          System.out.println(messageId);
        }
      });
    }
  } finally {
    if (publisher != null) {
      // When finished with the publisher, shutdown to free up resources.
      publisher.shutdown();
    }
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:54,代码来源:PublisherExample.java


注:本文中的com.google.cloud.pubsub.v1.Publisher.shutdown方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。