How can I get a single message from the rabbitMq queue using PHP?

I need to catch only one actual message from one queue. The rabbit is trying to catch everyone. Simplified code below:

private function getSingleTask(){
$connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');

$channel = $connection->channel();
$channel->queue_declare('hello', false, false, false, false);

$callback = function($msg) {
 return $msg->body;
};

$channel->basic_qos(null, 1, null);
$channel->basic_consume('helloQueue', '', false, true, false, false, $callback);
$channel->wait(null, true, 5);
}

I send a few messages to the queue, but as soon as I execute part of the code below, it receives ALL messages from the queue and $ callbacks are only the first.

+4
source share
1 answer

The solution is easy ...

require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPConnection;

$connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel(); 
$result = ($channel->basic_get('helloQueue', true, null)->body);

The second argument of BTW for the "basic_get" method sets a confirmation for the message, so if the server is configured correctly, it can tell you whether there are messages in the queue or not, without receiving the message.

+3
source

Source: https://habr.com/ru/post/1608718/


All Articles