0
votes

I am persisting my domain events to my db. I have a webjob which reads those events and then forwards them to the proper queue/topic and then marks the message as IsForwarded in the db.

My question is does TopicClient.Send() and QueueClient.Send() guarantee delivery, and if it fails to deliver does it guarantee an exception so that my webjob forwarding events does not update the db? Essentially, i want to know how i can guarantee that messages are received by the service bus.

My current method of sending a message to a queue/topic is:

        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();
    }

Webjob:

        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();

        }
1

1 Answers

0
votes

If Send call completes successfully (without exception), it means that the message got delivered and broker accepted it. If delivery failed, Send will throw an exception.

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

Side note: in real-life code which sends many messages to the same topic, you should reuse TopicClient instance instead of creating and closing it for every message. It is thread-safe too.