Introduction

This guide demonstrates how to use the Azure Storage Queues client library for Java to interact with Azure Queues. Azure Queues is a service that enables you to store large numbers of messages that can be accessed from anywhere in the world via HTTP/HTTPS.

Prerequisites

Before you begin, ensure you have the following:

Setting up the Project

To get started, add the Azure Storage Queues client library for Java to your project. If you're using Maven, add the following dependency to your pom.xml file:

Maven Dependency pom.xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-queue</artifactId>
    <version>12.18.0</version>
</dependency>

If you are using Gradle, add this to your build.gradle file:

Gradle Dependency build.gradle
implementation 'com.azure:azure-storage-queue:12.18.0'

Connecting to the Queue

To connect to your Azure Storage Queue, you need a connection string or a shared access signature (SAS) token. You can find your connection string in the Azure portal under your storage account's "Access keys" section.

Security Best Practice: Avoid hardcoding connection strings directly in your code. Use environment variables, configuration files, or Azure Key Vault for secure management.

Here's how to create a QueueClient using a connection string:

Java Code QueueClient Example
import com.azure.storage.queue.QueueClient;
import com.azure.storage.queue.QueueClientBuilder;

public class QueueConnection {

    // Replace with your actual connection string
    private static final String CONNECTION_STRING = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
    private static final String QUEUE_NAME = "my-sample-queue";

    public static void main(String[] args) {
        try {
            QueueClient queueClient = new QueueClientBuilder()
                .connectionString(CONNECTION_STRING)
                .queueName(QUEUE_NAME)
                .buildClient();

            System.out.println("Successfully created QueueClient for queue: " + QUEUE_NAME);

            // You can now use queueClient to interact with the queue
            // For example: queueClient.create();

        } catch (Exception e) {
            System.err.println("Error creating QueueClient: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Managing Queues

You can perform operations such as creating, deleting, and listing queues using the QueueClient.

Creating a Queue

Java Code Create Queue Example
// Assuming queueClient is already initialized
if (queueClient.exists()) {
    System.out.println("Queue '" + QUEUE_NAME + "' already exists.");
} else {
    queueClient.create();
    System.out.println("Queue '" + QUEUE_NAME + "' created successfully.");
}

Deleting a Queue

Java Code Delete Queue Example
// Assuming queueClient is already initialized
queueClient.delete();
System.out.println("Queue '" + QUEUE_NAME + "' deleted successfully.");

Managing Messages

The core functionality of Azure Queues involves sending, retrieving, and deleting messages.

Sending a Message

Messages are stored as strings. The maximum size for a message is 64 KB.

Java Code Send Message Example
String messageText = "Hello, Azure Queues!";
queueClient.sendMessage(messageText);
System.out.println("Message sent: '" + messageText + "'");

Receiving and Processing Messages

When you receive a message, it becomes invisible to other consumers for a specified visibilityTimeout. You must then delete the message after processing it, or it will reappear in the queue.

Java Code Receive and Delete Message Example
// Receive up to 5 messages, with a visibility timeout of 1 minute (60 seconds)
queueClient.receiveMessages(5, Duration.ofSeconds(60)).forEach(message -> {
    System.out.println("Received message ID: " + message.getMessageId());
    System.out.println("Message content: " + message.getBody().toString());

    // Process the message here...
    System.out.println("Processing message...");

    // Delete the message after successful processing
    queueClient.deleteMessage(message.getMessageId(), message.getPopReceipt());
    System.out.println("Message deleted.");
});

Peek at Messages

You can also peek at messages without making them invisible. This is useful for inspecting messages without consuming them.

Java Code Peek Message Example
// Peek at the next message
queueClient.peekMessages(1).forEach(message -> {
    System.out.println("Peeked message ID: " + message.getMessageId());
    System.out.println("Message content: " + message.getBody().toString());
});

Advanced Topics

Conclusion

Azure Storage Queues provide a robust and scalable messaging solution. With the Java SDK, you can easily integrate queue functionality into your applications for decoupling services, asynchronous processing, and reliable communication.

For more detailed information, refer to the official Azure Storage Queues documentation.