PHP RabbitMQ setTimeout or other option to stop queue waiting

I need to create a simple queue manager to pass the number from the sender to the consumer. The Hello World tutorial provided by RabbitMQ covers nearly 70% of it.

But I need to change the queue so as not to forever wait for incoming messages. Or stop after a certain number of messages. I read and tried several solutions from another post, but it does not work.

rabbitmq AMQP :: consumume () is an undefined method. there is another method, wait_frame, but it is protected.

and another post is in python which I don't 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'); ?> 
+7
php wait rabbitmq amqp php-amqplib
source share
3 answers

Change wait () in while loop:

 $timeout = 55; while(count($channel->callbacks)) { $channel->wait(null, false, $timeout); } 
+6
source share

the wait function only works with sockets, we must 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; } } 
+5
source share

Here's how I did it to signal the queue in order to stop the consumption of incoming messages.

However, this may not be the right way to do this, as it gives an error and not exits correctly.

Please suggest the best answer, if any.

  $callback = function($msg) { echo " [x] Received ", $msg->body, "\n"; // if queue recieve 'stop', stop consume anymore messages if ($msg->body == 'stop'){ $channel->basic_cancel($queueName); } }; $channel->basic_consume($queueName, '', false, true, false, false, $callback); $timeout = 10; while(count($channel->callbacks)) { // $channel->wait(null, false, $timeout); $channel->wait(); } 
0
source share

All Articles