In this article, I want to share my practical experience implementing a second-level handler in Sitecore Message Bus.
While working on one of our projects, we needed a mechanism for handling messages between different applications. Sitecore implements this mechanism via the Sitecore Messaging Framework on Azure Service Bus. In this regard, the article by Árvai Mihály helped us a lot.
However, we needed to implement a second-level handler. As it turned out, the method is quite simple but not obvious.
Let’s see how you can do this.
First of all, you need to create a configuration file.
Here you have to pay attention to the Options section:
- <ErrorQueueAddress>Error</ErrorQueueAddress> — defines the queue to which the message will be sent if its processing fails.
- <MaxDeliveryAttempts>3</MaxDeliveryAttempts> — defines the number of attempts to receive messages by the first-level handler.
- <SecondLevelRetriesEnabled>true</SecondLevelRetriesEnabled> — allows the use of a second-level handler.
In our case, the second-level handler will be called after three unsuccessful attempts to receive a message by the first-level handler.
Now, you should create a contract for messages.
Then, you should create an empty class that will be used by the Rebus library.
The next step is to initialize our ExampleMessageBus with the help of Sitecore Initialize Pipeline.
To receive messages, you should create a handler and register it. You’ll need the Rebus library to do this.
In the handler, we inherit IMessageHandler <ExampleMessage> and IMessageHandler <IFailed <ExampleMessage>>. The second interface allows us to process messages when the message processing at the first level was unsuccessful. Here you can set a Defer for messages or send a notification that an error has occurred at the first level, or something else.
You should also register IMessageHandler<IFailed<ExampleMessage>> in the configurator.
So it’s done. Now you are able to use the second-level messaging in the Sitecore Service Bus.
P.S. Many thanks to a colleague of mine Mikhail Shishlyannikov who helped me with investigating this topic.