【发布时间】:2021-10-09 15:31:24
【问题描述】:
我们正在尝试将消息发布到 google pub 子主题,我正在使用来自 this git repository 的示例代码。
这里的问题是,只要从下面的代码发布一条消息,发布到主题的重复消息的数量就会呈指数级增长。 不知道为什么我会面临这种行为,但无法弄清楚示例代码或已创建的发布子主题是否存在问题。 有人可以帮助我了解这里发生了什么以及如何解决此问题。
public static void main(String... args) throws Exception {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String topicId = "your-topic-id";
publisherExample(projectId, topicId);
}
public static void publisherExample(String projectId, String topicId)
throws IOException, ExecutionException, InterruptedException {
TopicName topicName = TopicName.of(projectId, topicId);
Publisher publisher = null;
try {
// Create a publisher instance with default settings bound to the topic
publisher = Publisher.newBuilder(topicName).build();
String message = "{\r\n" +
" \"errorCodeFormat\": \"NF-123-ABC000\"\r\n" +
"}";
ByteString data = ByteString.copyFromUtf8(message);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
// Once published, returns a server-assigned message id (unique within the topic)
ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
String messageId = messageIdFuture.get();
System.out.println("Published message ID: " + messageId);
} finally {
if (publisher != null) {
// When finished with the publisher, shutdown to free up resources.
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
}
}
}
}
下面是正在使用的订阅者代码
public static void subscribeAsyncExample(String projectId, String subscriptionId) throws TimeoutException {
ProjectSubscriptionName subscriptionName =
ProjectSubscriptionName.of(projectId, subscriptionId);
// Instantiate an asynchronous message receiver.
MessageReceiver receiver =
(PubsubMessage message, AckReplyConsumer consumer) -> {
// Handle incoming message, then ack the received message.
System.out.println("Id: " + message.getMessageId());
System.out.println("Data: " + message.getData().toStringUtf8());
consumer.ack();
};
System.out.println("You are in consumer listener");
Subscriber subscriber = null;
// try {
subscriber = Subscriber.newBuilder(subscriptionName, receiver).build();
// Start the subscriber.
subscriber.startAsync().awaitRunning();
System.out.printf("Listening for messages on %s:\n", subscriptionName.toString());
// Allow the subscriber to run for 30s unless an unrecoverable error occurs.
subscriber.awaitTerminated(30, TimeUnit.MINUTES);
// } catch (TimeoutException timeoutException) {
// // Shut down the subscriber after 30s. Stop receiving messages.
// subscriber.stopAsync();
// System.out.println("Subscriber state: {}"+ subscriber.state());
// }
}
【问题讨论】:
-
您如何确定“发布到该主题的重复消息数量呈指数增长”?是您的订阅者多次收到消息,还是您使用该主题的指标?如果是前者,你能分享你的订阅者代码吗?
-
@Kamal Aboul-Hosn 当我对使用上述代码发布的每 1 条消息说指数时,我看到主题上随机出现 5 到 7 条重复消息。我将更新上面的订阅者代码供您参考
-
重复的消息是不同的消息ID还是相同的ID?
-
@KamalAboul-Hosn 重复消息的消息 ID 不同,但有效负载数据保持不变。我发现的一种行为是发布的消息 ID 始终与重复消息的最后一条匹配
标签: java google-cloud-platform google-cloud-pubsub