Friday, 8 November 2024

Amazon SQS Java: Send and Receive Product Objects | Amazon SQS: Sending and Receiving Custom Objects

🚀 Master AWS Development with Java!

Subscribe to Ram N Java for more hands-on tutorials on AWS SDK and Java integration.

SUBSCRIBE TO THE CHANNEL

Introduction

Amazon Simple Queue Service (SQS) is a fundamental tool for building decoupled, distributed systems. While SQS natively handles strings, most real-world applications need to exchange complex data. In this tutorial, we demonstrate how to use the AWS SDK for Java and Jackson to send and receive custom Product objects by serializing them into JSON.

Step 1: Maven Dependencies

To follow along, ensure your pom.xml includes the AWS SDK for SQS and the Jackson library for JSON processing:

<!-- AWS SDK for SQS -->
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>sqs</artifactId>
    <version>2.x.x</version>
</dependency>

<!-- Jackson for JSON -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

Step 2: Defining the Product Class

Create a simple POJO to represent your data. This class should have a default constructor and standard getters/setters for Jackson to work correctly.

public class Product {
    private int id;
    private String name;
    private double price;
    // Getters and Setters
}

Step 3: The Producer (Sending Objects)

The producer converts the Java object to a JSON string using ObjectMapper and sends it to the SQS queue using the SendMessageRequest.

ObjectMapper mapper = new ObjectMapper();
String productJson = mapper.writeValueAsString(new Product(1, "iPhone 16 Pro Max", 125000));

SendMessageRequest sendMsgRequest = SendMessageRequest.builder()
    .queueUrl(queueUrl)
    .messageBody(productJson)
    .build();
sqsClient.sendMessage(sendMsgRequest);

Step 4: The Consumer (Receiving Objects)

The consumer receives the message, extracts the JSON body, and deserializes it back into a Product object. Don't forget to delete the message after successful processing!

ReceiveMessageResponse response = sqsClient.receiveMessage(receiveRequest);
for (Message message : response.messages()) {
    Product product = mapper.readValue(message.body(), Product.class);
    System.out.println("Processing: " + product.getName());
    
    // Delete message from queue
    DeleteMessageRequest deleteRequest = DeleteMessageRequest.builder()
        .queueUrl(queueUrl)
        .receiptHandle(message.receiptHandle())
        .build();
    sqsClient.deleteMessage(deleteRequest);
}

Conclusion

By combining the AWS SDK with Jackson, you can easily pass complex data structures through Amazon SQS. This pattern is essential for microservices architectures where different components need to exchange typed data asynchronously. Happy coding!

No comments:

Post a Comment

Tutorials