Integrating Amazon Simple Queue Service (SQS) with a Spring Boot application

Integrating Amazon Simple Queue Service (SQS) with a Spring Boot application enables asynchronous communication between microservices, enhancing scalability and reliability. Here's a step-by-step guide to set up both a producer and a consumer using Spring Boot.


1. Set Up AWS SQS Queue

  • Create a Queue: Log in to the AWS Management Console, navigate to the SQS service, and create a new queue. Choose between a Standard or FIFO queue based on your requirements.


2. Configure Your Spring Boot Project

  • Add Dependencies: Include the necessary dependencies in your pom.xml (for Maven) or build.gradle (for Gradle). For Maven, add:

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


For Gradle, add:

implementation 'io.awspring.cloud:spring-cloud-aws-starter:3.2.0'
implementation 'io.awspring.cloud:spring-cloud-aws-starter-sqs:3.2.0'


Prerequisites

Application Properties: Add your AWS credentials and region to the application.properties or application.yml file:

aws.access.key=your_access_key
aws.secret.key=your_secret_key
aws.region=your_region
aws.sqs.queueName=your_queue_name


4. Implement the Producer

Service Class: Create a service to send messages to the SQS queue:

@Service
public class SqsProducer {

    @Value("${aws.sqs.queueName}")
    private String queueName;

    private final AmazonSQS amazonSQSClient;
    private final ObjectMapper objectMapper;

    public SqsProducer(AmazonSQS amazonSQSClient, ObjectMapper objectMapper) {
        this.amazonSQSClient = amazonSQSClient;
        this.objectMapper = objectMapper;
    }

    public void sendMessage(String messageContent) {
        try {
            GetQueueUrlResult queueUrl = amazonSQSClient.getQueueUrl(queueName);
            Message message = new Message();
            message.setContent(messageContent);
            String jsonMessage = objectMapper.writeValueAsString(message);
            amazonSQSClient.sendMessage(queueUrl.getQueueUrl(), jsonMessage);
        } catch (Exception e) {
            // Handle exception
        }
    }
}


5. Implement the Consumer

Listener Class: Create a listener to process messages from the SQS queue:

@Service
public class SqsConsumer {

    @Value("${aws.sqs.queueName}")
    private String queueName;

    private final AmazonSQS amazonSQSClient;

    public SqsConsumer(AmazonSQS amazonSQSClient) {
        this.amazonSQSClient = amazonSQSClient;
    }

    @Scheduled(fixedDelay = 5000)
    public void receiveMessages() {
        try {
            String queueUrl = amazonSQSClient.getQueueUrl(queueName).getQueueUrl();
            ReceiveMessageResult receiveMessageResult = amazonSQSClient.receiveMessage(queueUrl);
            if (!receiveMessageResult.getMessages().isEmpty()) {
                com.amazonaws.services.sqs.model.Message message = receiveMessageResult.getMessages().get(0);
                // Process message
                amazonSQSClient.deleteMessage(queueUrl, message.getReceiptHandle());
            }
        } catch (Exception e) {
            // Handle exception
        }
    }
}


6. Run the Application

  • Main Class: Ensure your main application class is set up to run the Spring Boot application:

@SpringBootApplication
@EnableScheduling
public class SqsApplication {

    public static void main(String[] args) {
        SpringApplication.run(SqsApplication.class, args);
    }
}


  • Additional Resources AWS Documentation: For more detailed information, refer to the AWS SQS Developer Guide
  • GitHub Repository: Explore a practical example on GitHub
  • Video Tutorial: For a visual walkthrough, watch the following video:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete