CentOS 7
Sponsored Link

RabbitMQ : Use on PHP2016/09/03

 
This is an example to use RabbitMQ on PHP.
[1] Install some packages.
# install from EPEL

[root@dlp ~]#
yum --enablerepo=epel -y install composer php-bcmath
[2] Install AMQP client library.
[cent@dlp ~]$
composer require php-amqplib/php-amqplib

Using version ^2.6 for php-amqplib/php-amqplib
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing php-amqplib/php-amqplib (v2.6.3)
    Downloading: 100%

Writing lock file
Generating autoload files

[cent@dlp ~]$
composer install

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
[3] This is an example of sending message on PHP.
For example, connect with RabbitMQ user "serverworld", virtualhost "my_vhost".
[cent@dlp ~]$
vi send_msg.php
<?php
require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'serverworld', 'password', '/my_vhost');

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

$msg = new AMQPMessage('Hello RabbitMQ World!');
$channel->basic_publish($msg, '', 'Hello_World');
echo " [x] Sent 'Hello_World'\n";

$channel->close();
$connection->close();
?>

[cent@dlp ~]$
php send_msg.php

 [x] Sent 'Hello_World'
[4] This is an example of receiving message on PHP.
[cent@node01 ~]$
vi receive_msg.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'serverworld', 'password', '/my_vhost');
$channel = $connection->channel();

$channel->queue_declare('Hello_World', false, false, false, false);

echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

$callback = function($msg) {
    echo " [x] Received ", $msg->body, "\n";
};

$channel->basic_consume('Hello_World', '', false, true, false, false, $callback);

while(count($channel->callbacks)) {
    $channel->wait();
}
?>

[cent@node01 ~]$
php receive_msg.php

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