Try RabbitMQ + PHP on CentOS

1 minute read

A note when I tried RabbitMQ to introduce asynchronous processing in PHP.

  • This article uses CentOS7 and PHP7.3.

MQ preparation

RabbitMQ installation

yum --enablerepo=epel -y install rabbitmq-server
systemctl start rabbitmq-server
systemctl enable rabbitmq-server

Add user

rabbitmqctl add_user mquser password
rabbitmqctl list_users

Add virtual host

rabbitmqctl add_vhost myhost
rabbitmqctl list_vhosts

Permission settings

rabbitmqctl set_permissions -p myhost mquser ".*" ".*" ".*"
rabbitmqctl list_permissions -p myhost

PHP program preparation (sender & receiver)

php library installation

yum -y install --enablerepo=epel,remi-php73 php php-bcmath composer

composer installation

  • Implemented by general users
cd
mkdir mq
cd mq
composer require php-amqplib/php-amqplib
composer install

Sender

Send application creation

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, 'mquser', 'password', 'myhost');

$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();
?>

Send

php send_msg.php

Receiver

Create receiving application

vi receive_msg.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'mquser', 'password', 'myhost');
$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();
}
?>

Receive

php receive_msg.php
(CTRL+Stop at C)