欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-17 21:38:23
安装依赖 生产者 消费者 运行 查看队列 ......

安装依赖

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

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

生产者

# 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