说我有以下代码:
final ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
receiveMessageRequest.withMaxNumberOfMessages(10);
final List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
for (final Message message : messages) {
System.out.println("Message");
System.out.println(" MessageId: " + message.getMessageId());
System.out.println(" ReceiptHandle: " + message.getReceiptHandle());
System.out.println(" MD5OfBody: " + message.getMD5OfBody());
System.out.println(" Body: " + message.getBody());
for (final Entry<String, String> entry : message.getAttributes().entrySet()) {
System.out.println("Attribute");
System.out.println(" Name: " + entry.getKey());
System.out.println(" Value: " + entry.getValue());
}
}
根据我的理解,这段代码返回了10条消息。如果SQS队列中有1000条消息,那么我是否需要另一个循环?
有没有办法知道SQS队列大小?
答案 0 :(得分:2)
是的,您将需要另一个(外部)循环来继续获取10个批次的消息,直到没有剩余消息为止。您不需要知道队列的大小,只需使用while循环并进行迭代,直到得到没有消息的响应为止。
类似这样的东西:
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
receiveMessageRequest.withMaxNumberOfMessages(10);
List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
while (messages.size() > 0) {
for (final Message message : messages) {
System.out.println("Message");
System.out.println(" MessageId: " + message.getMessageId());
System.out.println(" ReceiptHandle: " + message.getReceiptHandle());
System.out.println(" MD5OfBody: " + message.getMD5OfBody());
System.out.println(" Body: " + message.getBody());
for (final Entry<String, String> entry : message.getAttributes().entrySet()) {
System.out.println("Attribute");
System.out.println(" Name: " + entry.getKey());
System.out.println(" Value: " + entry.getValue());
}
}
receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
receiveMessageRequest.withMaxNumberOfMessages(10);
messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
}
如果确实需要使消息数量仍在队列中,则可以向AWS开发工具包查询队列属性ApproximateNumberOfMessages
。喜欢:
GetQueueAttributesResult attrResult = sqs.getQueueAttributes(queueUrl, ["ApproximateNumberOfMessages"]);
System.out.println("Messages in queue: " + attrResult.getAttributes()["ApproximateNumberOfMessages"]);
答案 1 :(得分:0)
没有消息/空白消息可能会误导您。检索可能由于不同的原因而没有发生,例如: 由于另一位消费者的投票,可见性超时 SQS基础架构的分布式性质