What is MQ?

Short for Message Queue, Message queues (MQ) are an application-to-application communication method. MQ is a typical representation of the consumption-producer model, with one end constantly writing messages to a message queue and the other end reading messages from the queue.

RabbitMQ is a kind of MQ, this article introduces the use of PHP access RabbitMQ message queue method, combined with the form of examples to analyze RabbitMQ message queue related extension installation, queue establishment, queue binding, message sending, message receiving and other related operation skills, need friends can refer to

Extend the installation

PHP uses the AMQP protocol to access RabbitMQ, so install phP-pecl-amqp in the EPEL library

rpm -ivh http://mirror.neu.edu.cn/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
yum install php-pecl-amqp
Copy the code

Exchange to establish

<? php$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
$exchange->setName('exchange1');
$exchange->setType('fanout');
$exchange->declare(a);Copy the code

The queue to establish

<? php$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$queue = new AMQPQueue($channel);
$queue->setName('queue1');
$queue->declare(a);Copy the code

Queue bindings

<? php$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$queue = new AMQPQueue($channel);
$queue->setName('queue1');
$queue->declare(a);$queue->bind('exchange1'.'routekey');
Copy the code

Message is sent

<? php$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
$exchange->setName('exchange5');
$exchange->setType('fanout');
$exchange->declare(a);for($i = 0; $i < 2000000; $i{+ +)$exchange->publish("message $i"."routekey");
}
Copy the code

The message received

<? php$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$queue = new AMQPQueue($channel);
$queue->setName('queue1');
$queue->declare(a);$queue->bind('exchange1'.'routekey');
while (true) {
  $queue->consume(function($envelope.$queue) {echo $envelope->getBody(), PHP_EOL;
  }, AMQP_AUTOACK);
}
Copy the code

This message queue is not difficult!