Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to catch just one actual message from one queue. Rabbit tries to catch all of them. 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 throw few messages to the queue, but once i execute part of code below, it takes ALL messages from queue and $callbacks just the first.

like image 205
Tesmen Avatar asked Sep 23 '15 18:09

Tesmen


1 Answers

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);

BTW second argument of "basic_get" method sets acknowledge for message, so with proper server settings it can tell you whether queue has messages or not, without getting a message.

like image 64
Tesmen Avatar answered Oct 10 '22 03:10

Tesmen