大家好,我是考100分的小小码 ,祝大家学习进步,加薪顺利呀。今天说一说[学习笔记] RabbitMQ的简单使用,希望您对编程的造诣更进一步.
安装依赖
# composer.json
{
"require": {
"php-amqplib/php-amqplib": ">=2.9.0"
}
}
代码100分
代码100分> composer.phar install
[|||] -> (C)”>
生产者
# 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();
消费者
代码100分# 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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/9672.html