1. Set up your environment

Before you begin, you need an Azure account. If you don't have one, you can create a free account.

You also need an Azure Storage account. You can create one using the Azure portal.

Note: For this quickstart, a general-purpose v2 storage account is recommended.

2. Create a Java project

Create a new Java project in your preferred IDE or using a build tool like Maven or Gradle. If you're using Maven, you can create a project with the following command:

mvn archetype:generate -DgroupId=com.example -DartifactId=azure-queue-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Navigate to the project directory:

cd azure-queue-quickstart

3. Add the Azure Storage Queue client library

Add the Azure Storage Queue client library for Java to your project's dependencies. If you're using Maven, add the following to your pom.xml file:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-queue</artifactId>
    <version>12.15.0</version> <!-- Use the latest version available -->
</dependency>

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

implementation 'com.azure:azure-storage-queue:12.15.0' <!-- Use the latest version available -->

4. Get your Azure Storage account connection string

You need the connection string for your Azure Storage account to authenticate your application. You can find this in the Azure portal:

  1. Navigate to your storage account in the Azure portal.
  2. Under "Security + networking", select "Access keys".
  3. Copy one of the "Connection string" values.
Note: It's recommended to store connection strings securely, for example, using environment variables or Azure Key Vault, rather than hardcoding them directly into your application.

5. Write code to interact with queues

Replace the contents of your src/main/java/com/example/App.java file with the following Java code. Make sure to replace YOUR_CONNECTION_STRING with your actual storage account connection string and my-java-queue with your desired queue name.

import com.azure.storage.queue.QueueClient;
import com.azure.storage.queue.QueueClientBuilder;
import com.azure.storage.queue.models.QueueMessage;

public class App {
    public static void main(String[] args) {
        // Replace with your actual connection string
        String connectionString = System.getenv("AZURE_STORAGE_CONNECTION_STRING");
        // Or hardcode for quick testing (not recommended for production)
        // String connectionString = "YOUR_CONNECTION_STRING";

        if (connectionString == null || connectionString.isEmpty()) {
            System.err.println("AZURE_STORAGE_CONNECTION_STRING environment variable not set.");
            return;
        }

        // Replace with your desired queue name
        String queueName = "my-java-queue";

        try {
            // Create a QueueClient using the connection string and queue name
            QueueClient queueClient = new QueueClientBuilder()
                .connectionString(connectionString)
                .queueName(queueName)
                .buildClient();

            // Create the queue if it doesn't exist
            if (!queueClient.exists()) {
                queueClient.create();
                System.out.println("Queue '" + queueName + "' created.");
            } else {
                System.out.println("Queue '" + queueName + "' already exists.");
            }

            // --- Send messages ---
            String messageContent1 = "Hello from Java!";
            String messageContent2 = "This is the second message.";

            queueClient.sendMessage(messageContent1);
            System.out.println("Sent message: " + messageContent1);

            queueClient.sendMessage(messageContent2);
            System.out.println("Sent message: " + messageContent2);

            // --- Peek messages ---
            System.out.println("\nPeeking at messages:");
            queueClient.peekMessages().forEach(message -> {
                System.out.println("Peeked message ID: " + message.getMessageId() + ", Content: " + message.getMessageText());
            });

            // --- Receive and delete messages ---
            System.out.println("\nReceiving and deleting messages:");
            for (QueueMessage msg : queueClient.receiveMessages(2).getValue()) {
                System.out.println("Received message ID: " + msg.getMessageId() + ", Content: " + msg.getMessageText());
                // Delete the message after processing
                queueClient.deleteMessage(msg.getMessageId(), msg.getPopReceipt());
                System.out.println("Deleted message ID: " + msg.getMessageId());
            }

            // --- Check queue size ---
            int count = queueClient.getProperties().getApproximateMessagesCount();
            System.out.println("\nApproximate messages in queue: " + count);

            // --- Delete the queue ---
            // Uncomment the line below to delete the queue after execution
            // queueClient.delete();
            // System.out.println("Queue '" + queueName + "' deleted.");

        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

To use environment variables for the connection string:

  • Windows: set AZURE_STORAGE_CONNECTION_STRING=YOUR_CONNECTION_STRING
  • Linux/macOS: export AZURE_STORAGE_CONNECTION_STRING=YOUR_CONNECTION_STRING
Tip: For production applications, consider using Azure Key Vault to securely store and retrieve your connection string.

6. Run the application

You can build and run your Java application using Maven:

mvn clean install exec:java -Dexec.mainClass="com.example.App"

The output will show messages being sent, peeked, received, and deleted. If you uncommented the queue deletion part, the queue will also be removed.

7. Clean up resources

To avoid incurring further charges, delete the Azure Storage account you created for this quickstart. You can do this through the Azure portal.