Search code examples
amazon-web-servicesaws-java-sdk

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?


Solution

  • 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.