通过订阅从 Azure 服务总线接收消息

时间:2021-05-20 09:37:21

标签: java azureservicebus azure-servicebus-topics azure-servicebus-subscriptions

我推荐 this 通过订阅从我的 Azure 服务总线接收消息

我能够接收消息,但我一直在接收消息,直到我手动终止程序

我有一个超时选项,只想在超时之前接收消息。

如果您能解释以下代码的工作原理以及我如何修改以下代码以在特定时间范围内接收消息并在达到超时后停止接收,那将会很有帮助。

static void registerMessageHandlerOnClient(SubscriptionClient receiveClient, ExecutorService executorService) throws Exception {
    // register the RegisterMessageHandler callback
    receiveClient.registerMessageHandler(
            new IMessageHandler() {
                // callback invoked when the message handler loop has obtained a message
                public CompletableFuture<Void> onMessageAsync(IMessage message) {
                    // receives message is passed to callback
                    if (message.getLabel() != null &&
                            message.getContentType() != null &&
                            message.getLabel().contentEquals("Scientist") &&
                            message.getContentType().contentEquals("application/json")) {

                        byte[] body = message.getBody();
                        Map scientist = GSON.fromJson(new String(body, UTF_8), Map.class);

                        System.out.printf(
                                "\n\t\t\t\t%s Message received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s," +
                                        "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\",  \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n",
                                receiveClient.getEntityPath(),
                                message.getMessageId(),
                                message.getSequenceNumber(),
                                message.getEnqueuedTimeUtc(),
                                message.getExpiresAtUtc(),
                                message.getContentType(),
                                scientist != null ? scientist.get("firstName") : "",
                                scientist != null ? scientist.get("name") : "");
                    }
                    return receiveClient.completeAsync(message.getLockToken());
                }

                // callback invoked when the message handler has an exception to report
                public void notifyException(Throwable throwable, ExceptionPhase exceptionPhase) {
                    System.out.printf(exceptionPhase + "-" + throwable.getMessage());
                }
            },
            // 1 concurrent call, messages are auto-completed, auto-renew duration
            new MessageHandlerOptions(1, false, Duration.ofMinutes(1)),
            executorService);
}

1 个答案:

答案 0 :(得分:2)

这不能在您的订阅代码中完成。

您可以执行两种选项/解决方法

  • 不要连续向主题发送消息,在那里控制时间。
  • 创建一个 Timer Trigger 使 REST API 调用 Subscriptions - Create Or Update 使 EntityStatus = ReceiveDisabled 并使用类似的函数使 EntityStatus = {{1 }}。