1. 程式人生 > >使用PHP訪問RabbitMQ訊息佇列

使用PHP訪問RabbitMQ訊息佇列

擴充套件安裝


PHP訪問RabbitMQ實際使用的是AMQP協議,所以我們只要安裝epel庫中的php-pecl-amqp這個包即可


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


交換建立


<?php
$connection = new AMQPConnection();
$connection->connect();
 
$channel = new AMQPChannel($connection);
 
$exchange = new AMQPExchange($channel);
$exchange->setName('exchange1');
$exchange->setType('fanout');
$exchange->declare();
佇列建立


<?php
$connection = new AMQPConnection();
$connection->connect();
 
$channel = new AMQPChannel($connection);
 
$queue = new AMQPQueue($channel);
$queue->setName('queue1');
$queue->declare();
佇列繫結


<?php
$connection = new AMQPConnection();
$connection->connect();
 
$channel = new AMQPChannel($connection);
 
$queue = new AMQPQueue($channel);
$queue->setName('queue1');
$queue->declare();
 
$queue->bind('exchange1', 'routekey');
訊息傳送


<?php
$connection = new AMQPConnection();
$connection->connect();
 
$channel = new AMQPChannel($connection);
 
$exchange = new AMQPExchange($channel);
$exchange->setName('exchange5');
$exchange->setType('fanout');
$exchange->declare();
 
for($i = 0; $i < 2000000; $i++) {
  $exchange->publish("message $i", "routekey");
}
訊息接收


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

}