Installing RabbmitMQ+PHP RabbmitMQ application under centos

Keywords: PHP RPM Erlang RabbitMQ

You may be thinking about data distribution, non blocking jobs, or message push. Or you want to publish / subscribe, asynchronous tasks, work queues. All of these patterns are part of message queuing.

1. Install RabbmitMQ

wget https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.8/rabbitmq-server-3.6.8-1.el6.noarch.rpm

Get rpm, and you will find a lack of dependency during installation

Install dependent erlang

wget https://packages.erlang-solutions.com/erlang-solutions-1.0-1.noarch.rpm
rpm -Uvh erlang-solutions-1.0-1.noarch.rpm
yum install erlang

Be careful not to use the source of epel to install directly. The erlang version of the epel source is too low
Installation depends on socat

yum install socat

Last

rpm -Uvh rabbitmq-server-3.6.8-1.el6.noarch.rpm

2. RabbmitMQ Library of PHP

{
  "require": {
      "php-amqplib/php-amqplib": "2.6.*"
  }
}
comoser install

3.php+RabbmitMQ helloworld

//send.php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('hello', false, false, false, false);

$msg = new AMQPMessage('Hello World!');
$channel->basic_publish($msg, '', 'hello'); //Send a message to the hello channel

echo " [x] Sent 'Hello World!'\n";
$channel->close();
$connection->close();
//receive.php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

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

echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";
$callback = function($msg) {
  echo " [x] Received ", $msg->body, "\n";
};

//Receive messages from hello channel
$channel->basic_consume('hello', '', false, true, false, false, $callback);

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

4. operation

First run rabbmitMQ server

service rabbmitmq-server start

Suspend receive.php receive message processing

php receive.php

send message

##Another window to execute
php send.php

The above code builds a simple message queue


Messages are queued from send.php production (p) to consumers (c)

Note: when the command-line window receive.php is closed, the process will end. At this time, you need to use the
supservisor To run the receive.php script in the background. This part of the code can rewrite the scenario applied as a simple asynchronous queue task, but some additional processing is required under the demand of high concurrency and high availability. I'll talk about rabbmitMQ's competitive consumption pattern and the use of supervisor in a later article.

Posted by tmed on Sat, 30 Nov 2019 16:30:32 -0800