Java AWS - How to Send Messages to SQS Queues - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we will see how to send messages to SQS Queues using AWS Java SDK.
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.
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.
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.
Add software.amazon.awssdk dependency into your 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.
 % 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] 
...
..
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.
I created a standard queue with a name called My-Sample-Standard-Queue if you haven’t yet created see here.
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
Sending batch messages to SQS queue.
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
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.
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

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
Create SQS Queues
Install/setup AWS
AWS sqs developer guide
Happy Learning 🙂

Java AWS – How to read messages from SQS
Java AWS – How to Create SQS Standard and FIFO Queues
How to install AWS CLI on Windows 10
Python – AWS SAM Lambda Example
How to Copy Local Files to AWS EC2 instance Manually ?
Javascript – How to listObjects from AWS S3
How set AWS Access Keys in Windows or Mac Environment
How to connect AWS EC2 Instance using PuTTY
[Fixed] – Malformed Lambda proxy response –  status 502
Spring Boot RabbitMQ Consumer Messages Example
How add files to S3 Bucket using Shell Script
[Fixed] – Error: No changes to deploy. Stack is up to date
Spring Boot Kafka Consume JSON Messages Example
How to push docker image to docker hub ?
How to Send Mail Spring Boot Example

Java AWS – How to read messages from SQS
Java AWS – How to Create SQS Standard and FIFO Queues
How to install AWS CLI on Windows 10
Python – AWS SAM Lambda Example
How to Copy Local Files to AWS EC2 instance Manually ?
Javascript – How to listObjects from AWS S3
How set AWS Access Keys in Windows or Mac Environment
How to connect AWS EC2 Instance using PuTTY
[Fixed] – Malformed Lambda proxy response –  status 502
Spring Boot RabbitMQ Consumer Messages Example
How add files to S3 Bucket using Shell Script
[Fixed] – Error: No changes to deploy. Stack is up to date
Spring Boot Kafka Consume JSON Messages Example
How to push docker image to docker hub ?
How to Send Mail Spring Boot Example
 


Δ
 Install Java on Mac OS
 Install AWS CLI on Windows
 Install Minikube on Windows
 Install Docker Toolbox on Windows
 Install SOAPUI on Windows
 Install Gradle on Windows
 Install RabbitMQ on Windows
 Install PuTTY on windows
 Install Mysql on Windows
 Install Hibernate Tools in Eclipse
 Install Elasticsearch on Windows
 Install Maven on Windows
 Install Maven on Ubuntu
 Install Maven on Windows Command
 Add OJDBC jar to Maven Repository
 Install Ant on Windows
 Install RabbitMQ on Windows
 Install Apache Kafka on Ubuntu
 Install Apache Kafka on Windows