简体   繁体   中英

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. If there was a way to check the number of messages prior to my foreach statement I would avoid any errors. 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.

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.

Thanks

You can use PHP to count your array before looping through it with the count() function:

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

if (count($messages) > 0) {

    foreach ...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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