代码改变世界

[学习笔记] RabbitMQ的简单使用

2020-03-06 16:21  小伍2013  阅读(394)  评论(0编辑  收藏  举报

安装依赖

# composer.json
{
    "require": {
        "php-amqplib/php-amqplib": ">=2.9.0"
    }
}
> composer.phar install

(P) -> [|||] -> (C)

生产者

# send.php
<?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();

消费者

# receive.php
<?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 ($channel->is_consuming()) {
    $channel->wait();
}

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

运行

# shell 1
php receive.php

# shell 2
php send.php

查看队列

# Linux
sudo rabbitmqctl list_queues
# Windows
rabbitmqctl.bat list_queues