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

database

安装依赖

# composer.json

{

"require": {

"php-amqplib/php-amqplib": ">=2.9.0"

}

}

> composer.phar install

生产者

# send.php

<?php

require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLibConnectionAMQPStreamConnection;

use PhpAmqpLibMessageAMQPMessage;

$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!'

";

$channel->close();

$connection->close();

消费者

# receive.php

<?php

require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLibConnectionAMQPStreamConnection;

$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

";

$callback = function ($msg) {

echo ' [x] Received ', $msg->body, "

";

};

$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的简单使用 的全部内容, 来源链接: utcz.com/z/532540.html

回到顶部