Saturday, 9 November 2024

Amazon SQS Spring Boot Integration: Send and Receive Messages | Amazon SQS and Spring Boot

🚀 Master the Cloud with Ram N Java!

Subscribe for more in-depth AWS, Spring Boot, and Java tutorials!

SUBSCRIBE ON YOUTUBE

Introduction

Amazon Simple Queue Service (SQS) is a fully managed message queuing system that allows you to decouple your microservices. By using a message broker like SQS, services can communicate asynchronously, processing messages at their own pace. In this tutorial, we’ll use Spring Cloud AWS to simplify this integration.

Step 1: Prerequisites

Before we begin, ensure you have the following:

  • An active AWS Account.
  • An IAM User with programmatic access (Access Key and Secret Key).
  • A Spring Boot 3 application.

Step 2: Project Setup (pom.xml)

To handle dependencies efficiently, use the Spring Cloud AWS Bill of Materials (BOM) and include the SQS starter:

<dependency>
    <groupId>io.awspring.cloud</groupId>
    <artifactId>spring-cloud-aws-starter-sqs</artifactId>
</dependency>

Step 3: Configuration

In your application.properties, provide your AWS credentials and region. Then, create a configuration class to define the SqsTemplate:

@Bean
public SqsTemplate sqsTemplate(SqsAsyncClient sqsAsyncClient) {
    return SqsTemplate.builder()
            .sqsAsyncClient(sqsAsyncClient)
            .build();
}

Step 4: Sending Messages (Producer)

The SqsTemplate makes sending messages incredibly easy. Simply specify the queue name and the payload:

public void sendMessage(String message) {
    sqsTemplate.send(to -> to.queue("message-queue").payload(message));
}

Step 5: Receiving Messages (Consumer)

There are two ways to receive messages:

A. Using @SqsListener (Push-based)

Annotate a method to automatically listen for incoming messages. This is the simplest approach as the framework handles the polling for you.

@SqsListener("message-queue")
public void listen(String message) {
    System.out.println("Received: " + message);
}

B. Manual Polling (Pull-based)

Use sqsTemplate.receive() within a loop if you need more control over when messages are fetched.

Message Acknowledgement Modes

  • OnSuccess: Automatically deletes the message after successful processing.
  • Always: Deletes the message regardless of success or failure.
  • Manual: You must explicitly call acknowledgement.acknowledge().

Conclusion

By integrating Amazon SQS with Spring Boot, you've built a scalable, asynchronous communication bridge for your microservices. Whether using the push-based @SqsListener or pull-based SqsTemplate, Spring Cloud AWS makes cloud messaging straightforward and efficient.

No comments:

Post a Comment

Tutorials