简体   繁体   English

从SQS收到的消息数

[英]Number of messages received from SQS

Using Amazon's SQS and their PHP SDK I am receiving messages and deleting them just fine however if no messages are received I get an error when attempting to loop through the messages. 使用Amazon的SQS及其PHP SDK,我可以接收消息并删除它们,但是如果没有收到消息,尝试遍历消息时会收到错误消息。 If there was a way to check the number of messages prior to my foreach statement I would avoid any errors. 如果有一种方法可以在我的foreach语句之前检查消息数,则可以避免任何错误。 Obviously I can suppress the error and everything will proceed without a problem but I'd prefer not to. 显然,我可以抑制该错误,并且一切都会顺利进行,但我不希望这样做。

$result = $sqs->receiveMessage(array(
            'QueueUrl' => SQS_QUEUE,
            'MaxNumberOfMessages' => 10 ));

foreach ($result->get('Messages') as $message) {
    if (process_sqs($message['Body'])) {
        $deletemessage = $sqs->deleteMessage(array(
            'QueueUrl' => SQS_QUEUE,
            'ReceiptHandle' => $message['ReceiptHandle']));
    }
}

Basically after the $result is populated I would like to query the number of messages received, if over 0 then proceed to the foreach statement. 基本上,在填充$ result之后,我想查询接收到的消息数,如果超过0,则继续执行foreach语句。

I know I could use GetQueueAttributes prior to receiveMessage to get an estimate of the number of messages in the queue but I see no need to make an additional request while not guaranteeing I will actually receive any messages. 我知道我可以在receiveMessage之前使用GetQueueAttributes来获取队列中消息数量的估计,但是我看到无需提出额外的请求,而又不能保证我会实际收到任何消息。

Thanks 谢谢

You can use PHP to count your array before looping through it with the count() function: 您可以使用PHP对数组进行计数,然后再使用count()函数进行遍历:

$messages = $result->get('Messages');

if (count($messages) > 0) {

    foreach ...

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM