In this tutorial, we will see how to send messages to SQS Queues using AWS Java SDK.

Java Send Messages to SQS Queues:

We can send messages to SQS in 2 different ways that are sending a single message and sending a bunch of messages at a time.

Pre-Requisites:

  • Make sure you have an AWS account and valid credentials to access the resources.
  • Better you install the AWS CLI on your machine for troubleshooting.
  • Configure AWS credentials on your local machine.

Versions:

  • Java 14
  • AWS SDK 2.16.29

As part of this example, we are going to send messages to the SQS queue, messages can be sent to the SQS queue in two ways; single message and sending a bulk of messages at a time.

In this previous tutorial, we discussed that there were 2 different queries in AWS SQS that are Standard and FIFO queues and these two have significant differences, hence there also be differences while sending the messages to Standard and FIFO queues.

Java Send Messages to SQS Example:

Add software.amazon.awssdk dependency into your pom.xml.

pom.xml
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>sqs</artifactId>
</dependency>

The Amazon AWS SDK for Java is used to interact with AWS resources from a Java application.

Run the maven clean install command to download the dependencies.

Terminal
 % mvn clean install
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------< AWS_EXample:java-aws-examples >--------------------
[INFO] Building java-aws-examples 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
...
..

Pre-Requisites:

  • Make sure you have an AWS account and valid credentials to access the resources.
  • Better you install the AWS CLI on your machine for troubleshooting.
  • Configure AWS credentials on your local machine.

Send Single Messages to Standard Queue:

I created a standard queue with a name called My-Sample-Standard-Queue if you haven’t yet created see here.

SQS_Example.java
package com.otp;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.*;

public class SQS_Example {

    public static void main(String[] args) {
        String queue = "https://sqs.us-west-2.amazonaws.com/123456/My-Sample-Standard-Queue";
        SqsClient sqsClient = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();
        sendSingleMessage(sqsClient, queue);
        sqsClient.close();
    }

    public static void sendSingleMessage(SqsClient sqsClient, String queueUrl) {
        try {
            sqsClient.sendMessage(SendMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .messageBody("Hello world from Java!")
                    .delaySeconds(10)
                    .build());
            System.out.println("Message has been sent successfully");
        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}

Output:

Message has been sent successfully

Java AWS - How to Send Messages to SQS Queues Standard

Send Batch Messages to Standard Queue:

Sending batch messages to SQS queue.

SQS_Example.java
package com.otp;
import java.util.*;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.*;

public class SQS_Example {

    public static void main(String[] args) {
        SqsClient sqsClient = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();
        String queue = "https://sqs.us-west-2.amazonaws.com/123456/My-Sample-Standard-Queue"
        sendBatchMessages(sqsClient, queue);
        sqsClient.close();
    }

    public static void sendBatchMessages(SqsClient sqsClient, String queueUrl) {

        try {
            Collection<SendMessageBatchRequestEntry> messages = Arrays.asList(
                    SendMessageBatchRequestEntry.builder().id("id-1").messageBody("Hello 1").build(),
                    SendMessageBatchRequestEntry.builder().id("id-2").messageBody("Hello 2").build(),
                    SendMessageBatchRequestEntry.builder().id("id-3").messageBody("Hello 3").build()
            );
            SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
                    .queueUrl(queueUrl)
                    .entries(messages)
                    .build();
            sqsClient.sendMessageBatch(sendMessageBatchRequest);
            System.out.println("Messages has been sent successfully as a batch");
        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }
}

Output:

Messages has been sent successfully as a batch
Java AWS - How to Send Messages to SQS Queues Batch

Now send messages to the FIFO queue, it is as simple as a standard queue but here we need to pass some extra parameters with respect to the FIFO queue properties like message_ group_id and message_duplication_id.

Send Single Messages to FIFO Queue:

SQS_Example.java
package com.otp;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.*;

public class SQS_Example {

    public static void main(String[] args) {
        SqsClient sqsClient = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();
        String queue = "https://sqs.us-west-2.amazonaws.com/123456/My-FIFO-Queue.fifo";
        sendSingleFifoMessage(sqsClient, queue);
        sqsClient.close();
    }

    public static void sendSingleFifoMessage(SqsClient sqsClient, String queueUrl) {
        try {
            sqsClient.sendMessage(SendMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .messageBody("Hello world from Java!")
                    .messageGroupId("12345")
                    .messageDeduplicationId("123")
                    .build());
            System.out.println("Message has been sent successfully");
        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}

Output:

Message has been sent successfully
Java AWS - How to Send Messages to SQS Queues FIFO

Send Batch Messages to FIFO Queue:

SQS_Example.java
package com.otp;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.*;

import java.util.Arrays;
import java.util.Collection;

public class SQS_Example {

    public static void main(String[] args) {
        SqsClient sqsClient = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();
        String queue = "https://sqs.us-west-2.amazonaws.com/123456/My-FIFO-Queue.fifo";
        sendBatchFIFOMessages(sqsClient, queue);
        sqsClient.close();
    }

    public static void sendBatchFIFOMessages(SqsClient sqsClient, String queueUrl) {

        try {
            Collection<SendMessageBatchRequestEntry> messages = Arrays.asList(
                    SendMessageBatchRequestEntry.builder().id("id-1").messageBody("Hello 1")
                            .messageGroupId("12345").messageDeduplicationId("123").build(),
                    SendMessageBatchRequestEntry.builder().id("id-2").messageBody("Hello 2")
                            .messageGroupId("12345").messageDeduplicationId("123").build(),
                    SendMessageBatchRequestEntry.builder().id("id-3").messageBody("Hello 3").
                            messageGroupId("12345").messageDeduplicationId("123").build()
            );
            SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
                    .queueUrl(queueUrl)
                    .entries(messages)
                    .build();
            sqsClient.sendMessageBatch(sendMessageBatchRequest);
            System.out.println("Messages has been sent successfully as a batch");
        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }
}

Output:

Messages has been sent successfully as a batch
Java AWS - How to Send Messages to SQS Queues FIFO Batch

References:

Download Source From GIT:

Happy Learning 🙂

Leave A Comment