Spring Boot and Amazon SQS: Send and Receive Messages
Wire Amazon SQS into a Spring Boot service: the SDK dependency, queue configuration, sending messages, and consuming them with an SqsListener.
First, sign up for an AWS account if you don’t already have one. Then, navigate to the SQS dashboard and create a new queue.
Next, you’ll need to set up your Spring Boot application to use the AWS SDK for Java. In your “pom.xml” file, add the following dependency:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-sqs</artifactId>
</dependency>In your “application.properties”, add the following properties to specify your AWS access key and secret key:
aws.accessKeyId=YOUR_ACCESS_KEY
aws.secretKey=YOUR_SECRET_KEY
aws.region=YOUR_REGION
aws.queueName=YOUR_QUEUE_NAMECreate a configuration class to configure the AWS SDK and create a client for interacting with SQS. In this class, you’ll need to specify the region where your queue was created and the name of the queue:
@Configuration
public class SqsConfig {
@Value("${aws.accessKeyId}")
private String accessKey;
@Value("${aws.secretKey}")
private String secretKey;
@Value("${sqs.region}")
private String region;
@Value("${sqs.queueName}")
private String queueName;
@Bean
public AmazonSQSAsync amazonSQSAsync() {
BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonSQSAsyncClientBuilder builder = AmazonSQSAsyncClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(region);
return builder.build();
}
@Bean
public QueueMessagingTemplate queueMessagingTemplate(AmazonSQSAsync amazonSqs) {
return new QueueMessagingTemplate(amazonSqs);
}
}Now you’re ready to use the SQS client in your code. Inject the “QueueMessagingTemplate” bean into your class and use it to send messages to and receive messages from your SQS queue.
For example, here’s how you can send a message to the queue:
@Autowired
private QueueMessagingTemplate messagingTemplate;
public void sendMessage(String message) {
messagingTemplate.convertAndSend(queueName, message);}
And here’s how you can receive a message from the queue:
@SqsListener(value = "${sqs.queueName}", deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void receiveMessage(String message) {
// do something with the message}
That’s it! You can now use SQS in your Spring Boot application to communicate with other parts of your system asynchronously.
I hope this tutorial was helpful. Let me know if you have any questions.
Before wiring the client, it is worth knowing which queue you want: Standard vs FIFO explains the guarantees each one gives, and SQS vs Kinesis covers the case where a queue is the wrong tool entirely.
AuraLyrics
If you listen to music while you write code, AuraLyrics puts the lyrics over your editor instead of behind another window.
brew install --cask ozcberkay/tap/auralyricsNotes like this one, once a month
Java, AWS and what shipping a side product actually costs.