Implement SQS and SNS in spring boot

Mohit Kaushal
3 min readNov 4, 2022

AWS Messaging Support SQS

AWS provides us with two ways to send messages with two different approaches, i.e., Push and pull

  1. SQS (Using pull approach)
  2. SNS (Using push approach)

To know more about SQS and SNS, you can refer to below link:

https://mohitkaushal.medium.com/how-to-choose-between-sqs-and-sns-1247ff28c5a1

Implement SNS with Spring boot

SNS in spring boot

Step 1: Include the required dependency for AWS messaging in build.gradle:

implementation 'io.awspring.cloud:spring-cloud-starter-aws-messaging:2.3.5'

Step 2: Add AWS config in application.properties:

cloud.aws.credentials.access-key= ---your access key---
cloud.aws.credentials.secret-key= ---your secret key---
cloud.aws.region.static= ---your aws region---
cloud.aws.region.auto=false

Step 3: Create a configuration class for SNSClient:

package com.example.snsservice.configurations;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class AwsSNSConfig {
@Value("${cloud.aws.region.static}")
private String region;

@Value("${cloud.aws.credentials.access-key}")
private String awsAccessKey;

@Value("${cloud.aws.credentials.secret-key}")
private String awsSecretKey;

@Primary
@Bean
public AmazonSNSClient getAWSSNSClient() {
return (AmazonSNSClient) AmazonSNSClientBuilder.standard()
.withRegion(region)
.withCredentials(
new AWSStaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey, awsSecretKey)))
.build();
}
}

Step 4: Design a controller to publish messages to SNS:

package com.example.snsservice.sns.controllers;

import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.SubscribeRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SNSController {
private final static String TOPIC_ARN = "---your sns topic arn---";

@Autowired
AmazonSNSClient amazonSNSClient;

@PostMapping("/publish")
public String publishMessageToSNSTopic() {
PublishRequest publishRequest = new PublishRequest(TOPIC_ARN, buildMessageBody(),
"THis is demo from sns");
amazonSNSClient.publish(publishRequest);
return "notification send successfully.";
}

private String buildMessageBody() {
return "Hy I'm Mohit Kaushal, please support me."
+ "Thanks";
}

}

Step 5: Test our service using postman:

Push Message to SNS

Implement SQS with Spring boot

Follow Step 1 and Step 2 as we do in SNS implementation above:

Step 3: Setup configuration class for SQS:

package com.example.sqsservice.configurations;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQSAsync;
import com.amazonaws.services.sqs.AmazonSQSAsyncClientBuilder;
import io.awspring.cloud.messaging.core.QueueMessagingTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class SQSConfig {
@Value("${cloud.aws.region.static}")
private String region;
@Value("${cloud.aws.credentials.access-key}")
private String accessKey;
@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;
@Bean
public QueueMessagingTemplate queueMessagingTemplate() {
return new QueueMessagingTemplate(amazonSQSAsync());
}
@Bean
@Primary
public AmazonSQSAsync amazonSQSAsync() {
return AmazonSQSAsyncClientBuilder.standard().withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
.build();
}
}

Step 4: Create a Listener for our SQS queue to read data from it:

package com.example.sqsservice.sqs.controllers;

import com.amazonaws.services.sqs.AmazonSQSAsync;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import io.awspring.cloud.messaging.core.QueueMessageChannel;
import io.awspring.cloud.messaging.listener.SqsMessageDeletionPolicy;
import io.awspring.cloud.messaging.listener.annotation.SqsListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class SQSController {

@Autowired
private final AmazonSQSAsync amazonSqs;

@Autowired
public SQSController(final AmazonSQSAsync amazonSQSAsync) {
this.amazonSqs = amazonSQSAsync;
}

private String queueUrl = "---YOUR_QUEUE_URL---";

//listener
@SqsListener(value = "---YOUR_QUEUE_NAME---",deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void processMessage(String message) {
System.out.print("Message from SQS {" + message + "}");
}


//add new message in queue
@PostMapping("send-message")
public ResponseEntity<Object> sendMessage(@RequestBody Map<String,String> msg){
MessageChannel messageChannel
= new QueueMessageChannel(amazonSqs, queueUrl);

Message msgs = MessageBuilder.withPayload(msg.get("msg"))
.build();

long waitTimeoutMillis = 5000;
boolean sentStatus = messageChannel.send(msgs,waitTimeoutMillis);
return new ResponseEntity<>("Message Send Successfully", HttpStatus.OK);
}
}

Step 5: Test our application using postman:

Post a Message to SQS

Message Send to SQS Queue

Read the Message from SQS

Message Read by SQS

--

--

Mohit Kaushal

Hi, I’m Mohit Kaushal currently working as a software engineer and willing to make some changes by sharing knowledge with persons having the same interests.