Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP RabbitMQ setTimeout or other option to stop waiting for queue

I'm required to create a simple queue manager to pass a number from a sender to a consumer. Hello World tutorial provided by RabbitMQ covers almost 70% of it.

But I need to change the queue to not to forever waiting for incoming messages. Or stop waiting after certain amount of messages. I read and tried few solutions from other post, but it doesn't work.

rabbitmq AMQP::consume() - undefined method. there's another method, wait_frame but it is protected.

and other post is in python which I dont understand.

<?php

require_once __DIR__ . '/vendor/autoload.php';
require 'config.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

function recieveQueue($queueName){
    $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');

    // try{
    //  $connection->wait_frame(10);
    // }catch(AMQPConnectionException $e){
    //  echo "asdasd";
    // }

    $channel = $connection->channel();

    $channel->queue_declare($queueName, false, false, false, false);

    echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

    $callback = function($msg) {
        echo " [x] Received ", $msg->body, "\n";

    };

    // $tag = uniqid() . microtime(true);
    // $queue->consume($callback, $flags, $tag);

    $channel->basic_consume($queueName, '', false, true, false, false, $callback);

    // $channel->cancel($tag);

    while(count($channel->callbacks)) {
        $channel->wait();
    }

    echo "\nfinish";
}

recieveQueue('vtiger');

?>
like image 944
jedi Avatar asked Nov 26 '15 05:11

jedi


2 Answers

Modify wait() in while loop:

$timeout = 55;
while(count($channel->callbacks)) {
    $channel->wait(null, false, $timeout);
}
like image 84
Nick Avatar answered Sep 28 '22 06:09

Nick


wait function works only with sockets, we have to catch the exception:

 $timeout = 5;
    while (count($channel->callbacks)) {
        try{
            $channel->wait(null, false , $timeout);
        }catch(\PhpAmqpLib\Exception\AMQPTimeoutException $e){
            $channel->close();
            $connection->close();
            exit;
        }
    }
like image 28
Maurizio Brioschi Avatar answered Sep 28 '22 08:09

Maurizio Brioschi