yikai.shao Backend Dev Engineer

通过php使用rabbitmq消息队列

2018-03-02
php

rabbitmq官方文档

使用 php-amqplib 客户端

composer.json

{
    "require": {
        "php-amqplib/php-amqplib": ">=2.6.1"
    }
}

执行安装

composer install

创建 producer

<?php
// 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');

echo " [x] Sent 'Hello World!'\n";

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

创建 consumer

<?php
// 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";
};

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

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

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

测试方法:

首先,调用 consumer 来监听队列数据变化

php receive.php

Alt text

其次,调用 producer 往队列中写入消息

php send.php

Alt text

最后,查看执行 receive.php 的窗口

Alt text


概要