Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subscribe a SQS queue to a SNS topic in Java

When I create a new queue and subscribe it to a topic in Java, no message comes. The same via the AWS web console works fine.

I guess I have to confirm the subscription somehow, but the sns.confirmSubscription method needs a token - where shall I get it?

This is my Java code:

String queueURL = sqs.createQueue("my-queue").getQueueUrl();

sns.subscribe(myTopicARN, "sqs", queueURL);

sns.publish(myTopicARN, "{\"payload\":\"test\"}");

sqs.receiveMessage(queueURL).getMessages()
        .forEach(System.out::println);  // nothing

What am I doing wrong?

like image 471
Barney Avatar asked Feb 08 '19 11:02

Barney


People also ask

Is it possible to subscribe an SQS queue to an SNS topic?

You can subscribe one or more Amazon SQS queues to an Amazon Simple Notification Service (Amazon SNS) topic. When you publish a message to a topic, Amazon SNS sends the message to each of the subscribed queues. Amazon SQS manages the subscription and any necessary permissions.

Can SQS push to SNS?

SQS cannot publish messages to SNS. SQS can only store the messages. You have to pull the message using SQS Api's.

How do SQS and SNS work together?

When you subscribe an Amazon SQS queue to an Amazon SNS topic, you can publish a message to the topic and Amazon SNS sends an Amazon SQS message to the subscribed queue. The Amazon SQS message contains the subject and message that were published to the topic along with metadata about the message in a JSON document.


1 Answers

Check this out: https://aws.amazon.com/blogs/developer/subscribing-queues-to-topics/

You should subscribe like this:

Topics.subscribeQueue(sns, sqs, myTopicARN, queueURL);

This convinient method creates a policy for the subscription to allow the topic to send messages to the queue.

like image 165
ttulka Avatar answered Sep 28 '22 14:09

ttulka