CentOS 8
Sponsored Link

RabbitMQ : Use on PHP
2020/04/17
 
This is an example to use RabbitMQ on PHP.
[1] Install some packages.
# install from RabbitMQ, PowerTools

[root@dlp ~]#
dnf --enablerepo=centos-rabbitmq-38,PowerTools install librabbitmq-devel php-pear php-devel zlib-devel make
[root@dlp ~]#
pecl install amqp

[root@dlp ~]#
echo 'extension=amqp.so' >> /etc/php.ini

[2] This is an example of sending message on PHP.
For example, connect with RabbitMQ on [localhost] with a user [serverworld], virtualhost [my_vhost].
[cent@dlp ~]$
vi send_msg.php
<?php

$connection = new AMQPConnection();
$connection->setHost('127.0.0.1');
$connection->setVhost('/my_vhost');
$connection->setLogin('serverworld');
$connection->setPassword('password');
$connection->connect();

$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);

try {
    $routing_key = 'Hello_World';
    $queue = new AMQPQueue($channel);
    $queue->setName($routing_key);
    $queue->setFlags(AMQP_NOPARAM);
    $queue->declareQueue();

    $message = 'Hello RabbitMQ World!';
    $exchange->publish($message, $routing_key);
    echo " [x] Sent 'Hello_World'\n";
    $connection->disconnect();
}
catch (Exception $ex) {
    print_r($ex);
}

?>

[cent@dlp ~]$
php send_msg.php

 [x] Sent 'Hello_World'
[3] This is an example of receiving message on PHP.
[cent@node01 ~]$
vi receive_msg.php
<?php

$connection = new AMQPConnection();
$connection->setHost('10.0.0.30');
$connection->setVhost('/my_vhost');
$connection->setLogin('serverworld');
$connection->setPassword('password');
$connection->connect();

$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);

$callback_func = function(AMQPEnvelope $message, AMQPQueue $q) use (&$max_consume) {
    echo " [x] Received ", $message->getBody(), PHP_EOL;
    $q->nack($message->getDeliveryTag());
    sleep(1);
};

try {
    $routing_key = 'Hello_World';
    $queue = new AMQPQueue($channel);
    $queue->setName($routing_key);
    $queue->setFlags(AMQP_NOPARAM);
    $queue->declareQueue();
    echo ' [*] Waiting for messages. To exit press CTRL+C ', PHP_EOL;
    $queue->consume($callback_func);
}
catch(AMQPQueueException $ex) {
    print_r($ex);
}
catch(Exception $ex){
    print_r($ex);
}

echo 'Close connection...', PHP_EOL;
$queue->cancel();
$connection->disconnect();

?>

[cent@node01 ~]$
php receive_msg.php

 [*] Waiting for messages. To exit press CTRL+C
 [x] Received Hello RabbitMQ World!
Matched Content