AWS Developer Tools Blog

Subscribing an SQS Queue to an SNS Topic

In version 2.0.2.3 of the SDK we added an enhancement to the SDK to make it easier to subscribe an Amazon SQS queue to an Amazon SNS topic. You have always been able to subscribe queues to topics using the Subscribe method on the SNS client, but after you subscribed to the topic with your queue, you also had to set a policy on the queue using the SetQueueAttributes method from the SQS client. The policy gives permission to the topic to send a message to the queue.

With this new feature, you can call SubscribeQueue from the SNS client, and it will take care of both the subscription and setting up the policy. This code snippet shows how to create a queue and topic, subscribe the queue, and then send a message.

string queueURL = sqsClient.CreateQueue(new CreateQueueRequest
{
    QueueName = "theQueue"
}).QueueUrl;


string topicArn = snsClient.CreateTopic(new CreateTopicRequest
{
    Name = "theTopic"
}).TopicArn;

snsClient.SubscribeQueue(topicArn, sqsClient, queueURL);

// Sleep to wait for the subscribe to complete.
Thread.Sleep(TimeSpan.FromSeconds(5));

// Publish the message to the topic
snsClient.Publish(new PublishRequest
{
    TopicArn = topicArn,
    Message = "Test Message"
});

// Get the message from the queue.
var messages = sqsClient.ReceiveMessage(new ReceiveMessageRequest
{
    QueueUrl = queueURL,
    WaitTimeSeconds = 20
}).Messages;