我如何知道或确认 Azure 服务总线收到了中转消息?

How do i know or confirm that Azure service bus received the brokered message?

我正在将我的领域事件保存到我的数据库中。我有一个网络作业,它读取这些事件,然后将它们转发到正确的 queue/topic,然后在数据库中将消息标记为 IsForwarded。

我的问题是 TopicClient.Send() 和 QueueClient.Send() 是否保证交付,如果无法交付,是否保证出现异常,以便我的网络作业转发事件不会更新数据库?本质上,我想知道如何保证服务总线接收到消息。

我目前向 queue/topic 发送消息的方法是:

        private void PublishMessage(MessageQueue message, string queueName)
    {
        this.InitializeEventQueue(queueName, null);
        var client = TopicClient.CreateFromConnectionString(_connectionString, queueName);
        var brokeredMessage = this.CreateBrokeredMessage(message, message.MessageId.ToString());
        client.Send(brokeredMessage);
        client.Close();
    }

网络工作:

        var groups = this.GetNewMessages()
            .GroupBy(a => new { a.DuplicationDetectionId, a.TypeName });

        foreach (var group in groups)
        {

            //get the most recent message, which would be the last one of the group
            var message = group.OrderBy(a => a.CreateDate).Last();

            var queueName = this.GetQueueName(message.TypeName);
            this._messagingService.PublishMessage(message, queueName, 0);

            message.MarkAsForwarded();
            this._dbContext.Entry(message).State = EntityState.Modified;

            //mark as forwarded
            foreach (var storedEvent in group.Where(a => !a.IsForwarded))
                storedEvent.Delete();

            this._dbContext.SaveChanges();

        }

如果 Send 调用成功完成(无一例外),则表示消息已送达且代理已接受。如果发送失败,Send 将抛出异常。

Using any of the supported Service Bus API clients, send operations into Service Bus are always explicitly settled, meaning that the API operation waits for an acceptance result from Service Bus to arrive, and then completes the send operation.

docs

旁注:在向同一主题发送多条消息的实际代码中,您应该重用 TopicClient 实例,而不是为每条消息创建和关闭它。它也是线程安全的。