![](/img/trans.png)
[英]How to fetch the number of unacknowledged messages in a Pub/Sub Subscription via the Google Cloud Monitoring JAVA Client Library
[英]How to publish messages to Cloud Pub/Sub via the JAVA Client using a dependency?
我在 maven 包中編寫了以下方法:
public static void publishMessage(Publisher publisher, String message) throws ExecutionException, InterruptedException, TimeoutException {
ByteString data = ByteString.copyFromUtf8(message);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
String messageId = messageIdFuture.get(10L, TimeUnit.SECONDS);
LOG.info("Message Published! ID: {} Message: {}", messageId, message);
}
當我從 maven 包中的 Runner 主類調用此方法時,我能夠毫無問題地將消息發布到 Pub/Sub。 當我將此 maven 項目作為 SBT 項目中的依賴項加載並嘗試調用此方法時,執行在以下行超時: messageIdFuture.get(10L, TimeUnit.SECONDS);
或者如果我使用沒有超時配置的語句,就會無限期地卡住。
我正在以這種方式構建發布者:
public static Publisher getPublisher(String projectId, String topicId) throws IOException {
TopicName topicName = TopicName.of(projectId, topicId);
return Publisher.newBuilder(topicName).build();
}
我有一種預感,這個問題與執行程序和線程池有關,其中控制沒有以我想要的方式流動。
其他實驗:我嘗試通過運行publisher.publish(pubsubMessage);
避免future.get()
publisher.publish(pubsubMessage);
其次是publisher.shutdown();
因為關閉會發布所有本地排隊的消息。 即便如此,消息還是通過 Runner 類發布,並且 SBT 應用程序的執行會無限期地卡在publisher.shutdown();
在messagesWaiter.waitComplete();
內部使用wait()
messagesWaiter.waitComplete();
請注意:
正在使用的 JAVA 客戶端版本:1.108.1
我主要遵循 JAVA Client 文檔本身。 鏈接: https : //cloud.google.com/pubsub/docs/samples/pubsub-quickstart-publisher
升級到適用於 Cloud Pub/Sub 的 Java 客戶端庫的最新版本有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.