DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • What Are the 7 Rs of Cloud Migration Strategy?
  • Are You Tracking Kubernetes Applications Effectively?
  • Optimize AWS Solution Architecture for Performance Efficiency
  • Monitoring and Logging in Cloud Architecture With Python

Trending

  • DZone's Article Submission Guidelines
  • Docker Base Images Demystified: A Practical Guide
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • The Modern Data Stack Is Overrated — Here’s What Works
  1. DZone
  2. Data Engineering
  3. Databases
  4. Messaging in AWS Using SNS and SQS

Messaging in AWS Using SNS and SQS

Learn how to use asynchronous messaging in AWS using SNS and SQS.

By 
Randhir Singh user avatar
Randhir Singh
·
Feb. 19, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
13.8K Views

Join the DZone community and get the full member experience.

Join For Free

There are two main communication paradigms in event-driven architectures used in microservices design. 

  • Queueing provides a messaging system to integrate two different services.
  • Publish/subscribe messaging is a form of asynchronous service-to-service communication used in microservices architectures. In contrast to queueing, publish/subscribe messaging allows multiple consumers to receive each message in a topic. 

They allow us to de-couple producers and consumers of messages. By combining publish/subscribe messaging systems with queueing systems, we can build fault-tolerant, scalable, resilient, and reactive application architectures. Amazon Web Services (AWS) offers a number of services which provide these two communication paradigms. In this article, we will learn how to program AWS services – Simple Notification Service (SNS) for publish/subscribe messaging and Simple Queue Service (SQS) for queueing using AWS SDK in Java.

System Architecture

We have an application which needs to publish notifications if there is a change. This change is published to a topic in SNS. There are different subscription mechanisms available for an SNS topic – SQS being one of them. We will use an SQS queue to receive change notifications. An application may poll SQS queues for any message.

article image

Implementation

To develop and deploy the system, we'll need following infrastructure components:

  1. SNS topic.
  2. SQS queue.
  3. Subscription to the topic.
  4. Permission for SNS to publish to the SQS queue.

We will use Terraform to provision the infrastructure on AWS. Terraform is an open-source infrastructure as code software tool created by HashiCorp. 

SNS Topic

Let's create the SNS topic. To create an SNS topic we only need to provide a name. 

JSON
 




x


 
1
resource "aws_sns_topic" "config_updates" {
2
  name = "config-updates-topic"
3
}


We need permission to publish to this SNS topic. In our architecture, an application will publish change notifications to the topic. The application will use a user account with permissions to publish to the topic.

SQS Queue

We have to provide a name for the queue and a policy which allows SNS to send messages to the queue. 

JSON
 




xxxxxxxxxx
1


 
1
resource "aws_sqs_queue" "config_updates" {
2
  name = "config-updates-listener"
3
}


Next, create a subscription of the SNS topic for the SQS queue.

JSON
 




xxxxxxxxxx
1


 
1
resource "aws_sns_topic_subscription" "sqs" {
2
  topic_arn = aws_sns_topic.config_updates.arn
3
  protocol  = "sqs"
4
  endpoint  = aws_sqs_queue.config_updates.arn
5
}


Next, allow SNS to publish messages to the queue.

JSON
 




xxxxxxxxxx
1
24


 
1
resource "aws_sqs_queue_policy" "test" {
2
  queue_url = aws_sqs_queue.config_updates.id
3

          
4
  policy = <<POLICY
5
{
6
  "Version": "2012-10-17",
7
  "Id": "sqspolicy",
8
  "Statement": [
9
    {
10
      "Sid": "First",
11
      "Effect": "Allow",
12
      "Principal": "*",
13
      "Action": "sqs:SendMessage",
14
      "Resource": "${aws_sqs_queue.config_updates.arn}",
15
      "Condition": {
16
        "ArnEquals": {
17
          "aws:SourceArn": "${aws_sns_topic.config_updates.arn}"
18
        }
19
      }
20
    }
21
  ]
22
}
23
POLICY
24
}


Creating the Infrastructure

Let us run our Terraform scripts to create the infrastructure.

Java
 




xxxxxxxxxx
1


 
1
terraform init
2
terraform plan
3
terraform apply


The output of terraform apply provides us the SQS Queue URL and the SNS topic ARN that we will use in our application.

Develop the Application

Next, we develop our application that will publish a notification to an SNS topic and also poll an SQS queue to receive messages. We will use Java and the AWS SDK to develop our application.

Send Notifications to an SNS Topic

Java
 




xxxxxxxxxx
1
51


 
1
import com.randhirks.sns.model.ChangeNotification;
2
import com.randhirks.sns.model.NotificationRequest;
3
import org.springframework.beans.factory.annotation.Value;
4
import org.springframework.stereotype.Service;
5
import software.amazon.awssdk.regions.Region;
6
import software.amazon.awssdk.services.sns.SnsClient;
7
import software.amazon.awssdk.services.sns.model.PublishRequest;
8
import software.amazon.awssdk.services.sns.model.PublishResponse;
9
import software.amazon.awssdk.services.sns.model.SnsException;
10

          
11
@Service
12
public class NotificationService {
13

          
14
    @Value("${sns.topic.arn}")
15
    private String topicArn;
16

          
17
    @Value("${aws.region}")
18
    private String awsRegion;
19

          
20
    private SnsClient snsClient;
21

          
22
    private void init() {
23
        snsClient = SnsClient.builder()
24
                .region(Region.of(awsRegion))
25
                .build();
26

          
27
    }
28

          
29
    public ChangeNotification sendNotification(NotificationRequest notificationRequest) {
30

          
31
        ChangeNotification changeNotification = ChangeNotification.builder()
32
                .sentMessage(notificationRequest.getMessage()).build();
33

          
34
        try {
35
            init();
36

          
37
            PublishRequest request = PublishRequest.builder()
38
                    .message(notificationRequest.getMessage())
39
                    .topicArn(topicArn)
40
                    .build();
41

          
42
            PublishResponse result = snsClient.publish(request);
43
            System.out.println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());
44
            changeNotification.setId(result.messageId());
45
        } catch (SnsException e) {
46
            System.err.println(e.awsErrorDetails().errorMessage());
47
        }
48
        return changeNotification;
49
    }
50
}


Receive Messages From an SQS Queue

Java
 




xxxxxxxxxx
1
47


 
1
import com.google.gson.Gson;
2
import com.randhirks.sns.model.ChangeNotification;
3
import com.randhirks.sns.model.SNSMessage;
4
import org.springframework.beans.factory.annotation.Value;
5
import org.springframework.stereotype.Service;
6
import software.amazon.awssdk.regions.Region;
7
import software.amazon.awssdk.services.sqs.SqsClient;
8
import software.amazon.awssdk.services.sqs.model.Message;
9
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
10
import software.amazon.awssdk.services.sqs.model.SqsException;
11

          
12
@Service
13
public class NotificationListener {
14

          
15
    @Value("${aws.region}")
16
    private String awsRegion;
17

          
18
    @Value("${sqs.id}")
19
    private String queueUrl;
20

          
21
    private SqsClient sqsClient;
22

          
23
    private void init() {
24
        sqsClient = SqsClient.builder()
25
                .region(Region.of(awsRegion))
26
                .build();
27
    }
28

          
29
    public ChangeNotification receiveMessage(ChangeNotification changeNotification) {
30
        try {
31
            init();
32
            ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
33
                    .queueUrl(queueUrl)
34
                    .maxNumberOfMessages(1)
35
                    .build();
36

          
37
            Message message = sqsClient.receiveMessage(receiveMessageRequest).messages().get(0);
38
            Gson gson = new Gson();
39
            SNSMessage snsMessage = gson.fromJson(message.body(), SNSMessage.class);
40
            changeNotification.setReceivedMessage(snsMessage.getMessage());
41
        } catch (SqsException e) {
42
            System.err.println(e.awsErrorDetails().errorMessage());
43
        }
44
        return changeNotification;
45
    }
46
}


The complete code is available in my GitHub repo. Run the application as a Spring Boot application and hit the application URL to send a message. The output shows the received message from the SQS Queue.

Conclusion

In this article, we reviewed two important communication mechanisms in event-driven programming. We implemented an architecture on AWS leveraging the services – SNS and SQS – that implement these communication mechanisms. We provided a sample Java application using the AWS SDK to send and receive messages from our system.

AWS application Amazon Web Services Architecture microservice

Opinions expressed by DZone contributors are their own.

Related

  • What Are the 7 Rs of Cloud Migration Strategy?
  • Are You Tracking Kubernetes Applications Effectively?
  • Optimize AWS Solution Architecture for Performance Efficiency
  • Monitoring and Logging in Cloud Architecture With Python

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!