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

安装依赖

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

生产者

# send.php
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
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

你可能感兴趣的:([学习笔记] RabbitMQ的简单使用)