[英]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.当我创建一个新队列并将其订阅到 Java 主题时,没有消息出现。 The same via the AWS web console works fine.同样通过 AWS Web 控制台工作正常。
I guess I have to confirm the subscription somehow, but the sns.confirmSubscription
method needs a token - where shall I get it?我想我必须以某种方式确认订阅,但是sns.confirmSubscription
方法需要一个令牌——我应该从哪里得到它?
This is my Java code:这是我的Java代码:
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?我究竟做错了什么?
Check this out: https://aws.amazon.com/blogs/developer/subscribing-queues-to-topics/看看这个: 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.这种方便的方法为订阅创建了一个策略,以允许主题向队列发送消息。
subscribing the queue to sns does not automatically create a policy to allow sns to send messages to the queue (based on my experience with sns/sqs) so you need to create the policy yourself and give permission to sns to send messages to your queue this is an example on how to do it using queue url , queue arn and topic arn将队列订阅到 sns 不会自动创建允许 sns 将消息发送到队列的策略(根据我使用 sns/sqs 的经验),因此您需要自己创建策略并授予 sns 将消息发送到您的队列的权限是关于如何使用队列 url 、队列 arn 和主题 arn 进行操作的示例
import static com.amazonaws.auth.policy.Principal.All;
import static com.amazonaws.auth.policy.Statement.Effect.Allow;
import static com.amazonaws.auth.policy.actions.SQSActions.SendMessage;
import static com.amazonaws.auth.policy.conditions.ArnCondition.ArnComparisonType.ArnEquals;
final Statement mainQueueStatements = new Statement(Allow) //imported above
.withActions(SendMessage) //imported above
.withPrincipals(All) //imported above
.withResources(new Resource(queueArn)) // your queue arn
.withConditions(
new Condition()
.withType(ArnEquals.name()) //imported above
.withConditionKey(SOURCE_ARN_CONDITION_KEY) //imported above
.withValues(topicArn) // your topic arn
);
final Policy mainQueuePolicy = ()
.withId("MainQueuePolicy")
.withStatements(mainQueueStatements);
final HashMap<QueueAttributeName, String> attributes = new HashMap<>();
attributes.put(QueueAttributeName.Policy.toString(), mainQueuePolicy.toJson());
amazonSQS.setQueueAttributes(new SetQueueAttributesRequest().withAttributes(attributes).withQueueUrl(queueUrl)); // your queue url
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.