tp5使用RabbitMQ的使用记录(二)-- work queue
首先希望大家能够关注文档,文档上的内容比较全面,解释的也非常形象。我对此的记录就是写了一下对文档的理解,并且把文档上的内容在TP5中由重新写了一遍。
根据前面两篇文章我们知道了 生产者就是发送消息的客户端,队列就是一个缓冲区,用于存储消息。 消费者就是接受消息的应用程序
那发布订阅模式的核心思想就是生产者生产的消息不知道往队列里面发,而是发布到交换机上, 通过交换机在转存到一个匿名的队列中,只要队列里面的数据被消费了,这个队列就会删除,所以,队列是匿名的。
交换类型一个有direct, topic, headers 和fanout,我们先重点关注最后一种。
这种模式有以下几个关键的步骤,我也一一在代码中体现出来了。
创建连接、创建通道,创建交换机、创建数据对象、发布消息、关闭连接
接下来就是代码的演示
app\controller\Test.php
<?php
/**
* Created by Fanguochao
* User: fgc
* Date: 2021-08-23
* Time: 21:52
* Desc: rabbimtMQ测试类
*/
namespace app\controller;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use app\Library\RabbimtMQConnection;
class Test
{
// fanout 队列 又称为发布订阅模式
public function fanout(){
// 创建连接
$connection = new AMQPStreamConnection('localhost','5672','guest','guest');
// 创建通道
$channel = $connection->channel();
// 创建交换机
$channel->exchange_declare('logs','fanout',false,false,false);
// 要发送到队列里面的数据
$data = "info: Hello World";
// 创建消息对象
$msg = new AMQPMessage($data);
// 发布消息到rabbitmq
$channel->basic_publish($msg,'logs');
echo "发送消息成功\n";
// 关闭连接
$channel->close();
$connection->close();
}
}
相关的路由请求文件
这两个文件写完以后,发起一个请求
看到这一句话后,到rabbitmq管理网站上看队列里面有没有数据
接下来我们就要消费这个数据
因为消费数据是需要不断监听rabbitmq服务器传过来的数据,所有我选择有执行命令行来监听服务器。后期就可以执行这个命令脚本了。
app\Command\Recevie.php
<?php
declare (strict_types=1);
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use app\Library\RabbimtMQConnection;
use PhpAmqpLib\Message\AMQPMessage;
class Receive extends Command
{
protected function configure()
{
// 指令配置
$this->setName('receive')
->setDescription('rabbitmq 消费队列');
}
protected function execute(Input $input, Output $output)
{
// 指令输出
$output->writeln("RabbitMQ fanout消费队列开始启动……\n");
// 创建连接
$connection = new AMQPStreamConnection('localhost', '5672', 'guest', 'guest');
// 创建通道
$channel = $connection->channel();
// 创建交换机
$channel->exchange_declare('logs','fanout',false,false,false);
$output->writeln("RabbitMQ 交换机通道成功……\n");
// 创建一个匿名的消费队列
list($queue_name, ,) = $channel->queue_declare('',false,false,false,false);
// 消费队列绑定交换机
$channel->queue_bind($queue_name, 'logs');
$output->writeln("[*] Waiting for logs. To exit press CTRL+C\n");
$callback = function ($msg) use ($output) {
$output->writeln("通过RabbitMQ获取到消费者了,该条消息是: $msg->body \n");
};
$channel->basic_consume($queue_name, '', false, true, false, false, $callback);
while ($channel->is_open()) {
$channel->wait();
}
}
}
不同于之前work queue 模式中的情况,现在两个消费者都取到交换机发送到队列里面的数据了。而之前的模式是消费者1取奇数位,消费者2取偶数位 。这就是发布订阅这一种模式,只要你关联到了这个交换机上,这个消费者就能获取到交换机传递的全部数据。