I'm working on a client-server communication with PHP and RabbitMQ, using php-amqplib.
I have a producer script that looks like working fine, but my consumer does not receive anything.
I checked the entries in queue with sudo rabbitmqctl list_queues
and after each time I run the producer, the counter increments in it.
My consumer starts without any PHP errors and looks like waiting for messages. What not looks good it runs the callback script once with empty incoming message once at start - and than does not do anything.
php consumer.php
string(47) " [*] Waiting for messages. To exit press CTRL+C"
string(1) "
"
string(10) "Received: "
Here are my codes:
producer.php
public function sendDataToRabbitMQ()
{
$id = $_POST['id'];
$ipAddress = $_POST['ip'];
$date = date("Y-m-d h:i:s");
$status = false;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); //host: RABBITMQ_HOST
$channel = $connection->channel();
$channel->queue_declare('first_queue', false, true, false, false);
if(is_array($argv)) {
$data = implode(' ', array_slice($argv, 1));
}
if (empty($data)) {
$data = "$ipAddress,$id";
}
$msg = new AMQPMessage($data, array('delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
$channel->basic_publish($msg, '', 'first_queue');
echo " [x] Sent data:", "\n", $data, "\n";
$channel->close();
$connection->close();
return $result;
}
(changed host name constant to localhost for testing purposes)
consumer.php
<?php
require_once '../vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
class Consumer
{
private $token;
private function getQueue()
{
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('ban_queue', false, true, false, false);
var_dump(' [*] Waiting for messages. To exit press CTRL+C', "\n");
$callback = function($msg) {
$message = explode(',', $msg->body);
var_dump('Received: '.$message[0]);
$msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
};
$channel->basic_qos(null, 1, null);
$channel->basic_consume('first_queue', '', false, false, false, false, $callback);
while (count($channel->callbacks)) {
$channel->wait();
}
$channel->close();
$connection->close();
}
public function processResult()
{
$this->getQueue();
}
}
$consumer = new Consumer();
$consumer->processResult();
Why is it not working? I found the rabbitmq/php-amqplib tutorials and documentation pretty useless and completely struck on this issue for more than a half day now. Any help is appreciated.
UPDATE 1
I also checked this QA from this site, and my code is coherent to it.
After some time of research and testing I figured out the solution for the above problem:
I changed
$channel->basic_consume('first_queue', '', false, false, false, false, $callback);
to
$channel->basic_consume('first_queue', '', false, true, false, false, $callback);
and that made the trick.