Develop with Azure Service Bus (2): Queue

In this part, I will show you how to use Azure Service Bus through java sdk.

It has undergone major changes that the Azure Service Bus Client for Java updated to 1.0.0 version , relative to the past  0.9.7 version.

Here I provide 2 snippet code to show how to use the latest SDK to send/received messages in queue.

Prerequisites

  1. The connection string of Service Bus. And its shared access policy should have “Send” and “Listen” permission enabled.
  2. Java Runtime Environment
  3. Java IDE (Optional)

1, Configuration

Create a Maven project, and add the following dependency:
<dependency>
 <groupId>com.microsoft.azure</groupId>
 <artifactId>azure-servicebus</artifactId>
 <version>1.0.0</version>
</dependency>

2, Send message 

2.1 AzureServiceBusQueueSend.java

import com.microsoft.azure.servicebus.Message;
import com.microsoft.azure.servicebus.QueueClient;
import com.microsoft.azure.servicebus.ReceiveMode;
import com.microsoft.azure.servicebus.primitives.ConnectionStringBuilder;

public class AzureServiceBusQueueSend {
 
 private String connectionString;
 private QueueClient queueClient;
 private String queueName;
 
 public AzureServiceBusQueueSend(String connectionString, String queueName) throws Exception{
  this.connectionString = connectionString;
  this.queueName = queueName;
  this.queueClient = getQueueClient();
 }

// Create QueueClient object with connectionString and 'queueName'. Specify the receive mode as PEEKLOOK.
// In PEEKLOCK mode, the messages received from queue will be invisible temporarily.
// The following demo is just for test, it has not done anything.
public QueueClient getQueueClient() throws Exception {
  if(queueClient == null)
   return new QueueClient(new ConnectionStringBuilder(connectionString,queueName),ReceiveMode.PEEKLOCK);
  else
   return queueClient;
 }
//invoke the send() of queueClient to send message.
public void sendMessages(String clientName, int numMessages) throws Exception {
  for(int i = 0; i < numMessages; i ++) {
   String messageBody = "Message is " + i;
   Message message = new Message(messageBody.getBytes());
   queueClient.send(message);
   System.out.println("Client -> " + clientName + " ; Send -> " + messageBody);
  }
 }
 
 public void close() throws Exception{
  queueClient.close();
 }
 
 public static void main(String[] args) throws Exception {
  String connectionString = "your connection string";
  String queueName = "testqueue";
  AzureServiceBusQueueSend send = new AzureServiceBusQueueSend(connectionString, queueName);
  send.sendMessages("SendTest", 100);
  send.close();
 }
}
Sending message is not very complex, basically we pass the arguments 'connectionString' and 'queueName' to the constructor then get the instance of
queueClient by invoking the factory method getQueueClient().

3. receive message

3.1 AzureServiceBusQueueReceive.java

import com.microsoft.azure.servicebus.*;
import com.microsoft.azure.servicebus.primitives.ConnectionStringBuilder;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;

public class AzureServiceBusQueueReceive {

 private String connectionString;
 private QueueClient queueClient;
 private String queueName;

 public AzureServiceBusQueueReceive(String connectionString, String queueName) throws Exception{
  this.connectionString = connectionString;
  this.queueName = queueName;
  this.queueClient = getQueueClient();
 }
 
 //Create the QueueClient object with connectionString and 'queueName'.Specify the receive mode as PEEKLOCK.
 //In PEEKLOCK mode, the messages received from queue will be invisible temporarily.
 //it requires to delete the message after the QueueClient finish handling it.
public QueueClient getQueueClient() throws Exception {
  if(queueClient == null)
   return new QueueClient(new ConnectionStringBuilder(connectionString,queueName),ReceiveMode.PEEKLOCK);
  else
   return queueClient;
 }
//The new SDK differs from the old one in the main part of receiving messages
 //In the new SDK, it registers the messages handler to handle message asynchronously
//After that, calling complete()/completeAsyc() to finish and delete message.
private void receiveMessages(String clientName) throws Exception {
  queueClient.registerMessageHandler(new IMessageHandler() {

    public CompletableFuture<Void> onMessageAsync(IMessage message) {
     System.out.println("Client -> " + clientName + " ; Receive -> " + new String(message.getBody()));
     return queueClient.completeAsync(message.getLockToken()).thenRunAsync(()->{
      // Do something.
     });
    }

    public void notifyException(Throwable exception, ExceptionPhase phase) {
     System.out.println(phase + " encountered exception:" + exception.getMessage());
    }
   }, new MessageHandlerOptions(1, false, Duration.ofSeconds(30))
  );
 }
public void close() throws Exception{
  queueClient.close();
 }
 
 public static void main(String[] args) throws Exception {
  String connectionString = "Your connection string";
  String queueName = "testQueue"; 
  AzureServiceBusQueueReceive receive = new AzureServiceBusQueueReceive(connectionString, queueName);
  receive.receiveMessages("ReceiveClient1");
  Thread.sleep(20 * 1000);
  receive.close();
 }
}

3.2 More

Remember that the main differences between the SDK 1.0.0 version and the old one is in receiving message. For the  0.9.7 or more older version, it usually uses the pattern ‘while (true){// receive and handle messages } to receive/handle messages. But in SDK version 1.0.0, it will registers a messagehandler on QueueClient to receive message in a extra new thread.

queueClient.registerMessageHandler() requires 2 arguments, one is MessageHandler object (implement from IMessageHabdler interface), which should implement onMessageAsync() and notifyException(). The other one is MessageHandlerOptions object, that defines parameters on message processing :  the number of simultaneous requests, whether they are auto-completed, and automatic renewal.

4. Summary

This article describes how to use the latest SDK to use the Azure service bus, along with two complete code, to show you how to send and receive messages in the queue. If you have any questions, please contact us via aka.ms/devchat.

Leave a Reply

Your email address will not be published. Required fields are marked *