准备工作:
1. 搭建好rabbitmq服务器
2. 搭建好TP网站
一、 安装amqp包
composer require php-amqplib/php-amqplib
二、 网站中写一个发布者请求,往rabbitmq服务器发送数据。
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 app\Library\RabbimtMQConnection;
class Test
{
public function index()
{
$Rc = new RabbimtMQConnection();
list($connection, $channel) = $Rc->getConnection();
$channel->queue_declare('hello', false, false, false, false);
$msg = new AMQPMessage("Hello RabbitMQ");
$channel->basic_publish($msg, '', 'hello');
echo "[x] send 'hello world\n' ";
$channel->close();
$connection->close();
}
}
rabbitmq 连接工具类 : app\Library\RabbitMQConnection.php
<?php
/**
* Created by Fanguochao
* User: fgc
* Date: 2021-08-23
* Time: 22:36
* Desc: RabbitMQ 连接类
*/
namespace app\Library;
use PhpAmqpLib\Connection\AMQPStreamConnection;
class RabbimtMQConnection
{
public function __construct()
{
// TODO Something
}
public function getConnection()
{
try {
$connection = new AMQPStreamConnection('localhost', '5672', 'guest', 'guest');
$channel = $connection->channel();
return [$connection, $channel];
} catch (\Exception $e) {
return [null, null];
}
}
public function closeConnectionAndChanel($channel, $connection)
{
$channel->close();
$connection->close;
}
}
相关的路由请求文件
Route::get("send", 'test/index');
这两个文件写完以后,发起一个请求
看到这一句话后,到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 消费队列开始启动……\n");
$Rc = new RabbimtMQConnection();
list($connection, $channel) = $Rc->getConnection();
$output->writeln("RabbitMQ 创建通道成功……\n");
$channel->queue_declare('hello', false, false, false, false);
$callback = function ($msg) use ($output) {
$output->writeln("通过RabbitMQ获取到消费者了,该条消息是: $msg->body \n");
};
$channel->basic_consume('hello', '', false, true, false, false, $callback);
while ($channel->is_open()) {
$channel->wait();
}
}
}
这就是一个完整的rabbitmq 下的hello world的一个体验。后期我会根据rabbitmq的不同的工作模式在写不同的记录文章的。