Using Azure ServiceBus to keep data in sync across a distributed Blockchain system (2)

........     
This is the second part of this article - https://www.viorelspinu.com/2020/02/using-azure-servicebus-to-keep-data-in.html

First thing is to decide whether you need a topic or a queue. A topic received message and is able to broadcast those to multiple subscribers (you might want to use this for events related to blockchain - e.g. there is a new order that just got persisted to blockchain, here's the data, so that other actors involved can update their caches, for example), and a queue is a topic with a single receiver. Most of the times, I choose topics.


1. create your cloud infrastructure

First step is to create your topics, queues, subscriptions.
You know what queues and topics are. A subscription is an adapter between a topic and a receiver. It's job is to cache the messages before being sent to the subscriber. Also to resent a message if the subscriber fails to process it.



For the exact CLI commands, see here - https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-quickstart-cli, the "Use the Azure CLI to create resources" section.

2. sending and receiving messages to a topic 

First step is to create a SubscriptionClient and register some code as a message handler.



It's worth mentioning that there are two ways to subscribe to a topic or queue. The PEEK_LOCK mode, where a message gets received once again in case of error, and the RECEIVE_AND_DELETE mode, where a message is received just once (it's subscriber responsibility to correctly process it the first time). Usually, you'll want to use PEEK_LOCK, because you want to be sure the message is retried if something goes wrong. You can even choose to manually acknowledge the you have correctly processed a message (as opposed to having the library acknowledging on your behalf if no exceptions has occurred during the processing). 

subscription1Client = new SubscriptionClient(new ConnectionStringBuilder(connectionString, "BasicTopic/subscriptions/Subscription1"), ReceiveMode.PEEKLOCK);
As stated in my first part, you can do much more with ServiceBus. Here - https://github.com/Azure/azure-service-bus/blob/master/samples/Java/azure-servicebus/README.md - you can find some sample Java code for Duplicate Detection, Transaction Handling, Browsing the messages, handling the DeadLetterQueues.

Have fun !  


Comments