Messaging Via Azure Service bus | SendMessage and ScheduleMessage - GeeksforGeeks

27 Feb, 2020
In this section, we are going to discuss in brief about the data transfer methods to transfer data across Azure topics via service bus pooling. We can either send a normal message or a schedule based message. We will walk through each of these two basic type of messaging.
Azure Service Bus: Microsoft Azure Service Bus is a fully managed enterprise integration messaging service on cloud used to connect any applications, devices, and services running in the cloud to any other applications or services. This platform acts as a messaging backbone for applications over cloud and across any devices.
How does it work ? Data is transferred between different applications and services using messages. A message is in binary format and can contain JSON, XML, or just text. These messages are placed on to the service bus the application is connected with, so that all or specific users connected on, with this application, over the socket service connection open can receive the data transferred over the service bus.
Types of messaging: Data Messages transferred over the Azure service bus can be made of two major types, whether the data need to be sent on a specific schedule or is that required to be sent on immediate basis. Here we will discuss in detail about both these process of messaging. Each of these has its own specific methods for invoking the messaging process.
Send Message Immediate: The send() function call sends a message to the Azure Service Bus to which the current sender is connected to. This method makes a non-asynchronous call. You also have an asynchronous version to improve performance.Prototype:send( IMessage message )Sample Code:public static async sendMessage(content: Message): Promise<string> {       const serviceConnection = AzureServiceBus.createConnection();          const client = serviceConnection.createQueueClient(""                    + process.env.AZURE_SERVICEBUS_QUEUE);          const sender = client.createSender();    let response = "";       try {        const scheduledEnqueueTimeUtc             = moment().utc().add(1, "m").toDate();                  await sender.send( {body: JSON.stringify(content),                        label: "MyTopic"});                  await client.close();    } catch (error) {               } finally {        await serviceConnection.close();    }       return resp;}
Prototype:
send( IMessage message )
Sample Code:
public static async sendMessage(content: Message): Promise<string> {       const serviceConnection = AzureServiceBus.createConnection();          const client = serviceConnection.createQueueClient(""                    + process.env.AZURE_SERVICEBUS_QUEUE);          const sender = client.createSender();    let response = "";       try {        const scheduledEnqueueTimeUtc             = moment().utc().add(1, "m").toDate();                  await sender.send( {body: JSON.stringify(content),                        label: "MyTopic"});                  await client.close();    } catch (error) {               } finally {        await serviceConnection.close();    }       return resp;}
Schedule Message: This method sends a timer-based message to the Azure Service Bus the invoking sender is connected with. It enqueues the message into the bus to scheduled time message, the message is delivered to the receiver end. This is currently asynchronous process for better performance.Prototype:scheduleMessage( IMessage message, Instant scheduledEnqueueTimeUtc )Sample Code:public static async sendScheduleMessage(        content: Message): Promise<string> {       const serviceConnection =             AzureServiceBus.createConnection();          const client = serviceConnection.createQueueClient(            "" + process.env.AZURE_SERVICEBUS_QUEUE);          const sender = client.createSender();    let response = "";       try {        const scheduledEnqueueTimeUtc             = moment().utc().add(1, "m").toDate();                  const sequenceId = await sender.scheduleMessage(            scheduledEnqueueTimeUtc,            {body: JSON.stringify(content),            label: "MyTopic"});                  response = sequenceId.toString();        await client.close();    } catch (error) {               } finally {        await serviceConnection.close();    }       return resp;}This will raise an issue that the sequenceId value will go “undefined”. The Azure portal has provided with a fix that the message needs to be encoded and then placed into the service bus in order to get the correct sequenceId back.
Prototype:
scheduleMessage( IMessage message, Instant scheduledEnqueueTimeUtc )
Sample Code:
public static async sendScheduleMessage(        content: Message): Promise<string> {       const serviceConnection =             AzureServiceBus.createConnection();          const client = serviceConnection.createQueueClient(            "" + process.env.AZURE_SERVICEBUS_QUEUE);          const sender = client.createSender();    let response = "";       try {        const scheduledEnqueueTimeUtc             = moment().utc().add(1, "m").toDate();                  const sequenceId = await sender.scheduleMessage(            scheduledEnqueueTimeUtc,            {body: JSON.stringify(content),            label: "MyTopic"});                  response = sequenceId.toString();        await client.close();    } catch (error) {               } finally {        await serviceConnection.close();    }       return resp;}
This will raise an issue that the sequenceId value will go “undefined”. The Azure portal has provided with a fix that the message needs to be encoded and then placed into the service bus in order to get the correct sequenceId back.
Bug Fix:
import { DefaultDataTransformer }            from "@azure/amqp-common";......  const dt = new DefaultDataTransformer();  const sequenceId = await sender.scheduleMessage(        scheduledEnqueueTimeUtc,        {body: dt.encode(JSON.stringify(content)),        label: "MyTopic"});  response = sequenceId.toString();
Now you will receive the proper sequenceId, which you can use to cancel the message if required in the future using the following code piece.
CancelMessage: This method deleted the message placed in the service bus early using the scheduleMessage call. We need to send the sequenceNumber returned during the call as the only parameter for this method invocation. If the message is already delivered then we receive an error MessageNotFound which needs to be handled in the catch.
Prototype:
cancelScheduledMessage( long sequenceNumber )
Thus we have covered how we can communicate data by using the above two methods and placing the data requests either via a scheduled basis or non scheduled manner.
Cloud-Computing
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
How to redirect to another page in ReactJS ?
How to Insert Form Data into Database using PHP ?
How to pass data from child component to its parent in ReactJS ?