这里写自定义目录标题
thinkphp5/fastadmin 使用rabbitmq
打开tp5文档 找到自定义命令行
创建一个rabbitmq的启动命令
然后安装rabbitmq包
// composer
composer require php-amqplib/php-amqplib
找个工具目录建立一个rabbitmq的链接类
比如 app\api\library 目录 RabbitMQConnection.php
<?php
/**
* Desc: RabbitMQ 连接类
*/
namespace app\api\library;
use PhpAmqpLib\Connection\AMQPStreamConnection;
class RabbitMQConnection
{
public function __construct()
{
// TODO Something
}
public function getConnection()
{
try {
$connection = new AMQPStreamConnection('127.0.0.1', '5672', 'myuser', 'mypass');
$channel = $connection->channel();
return [$connection, $channel];
} catch (\Exception $e) {
return [null, null];
}
}
public function closeConnectionAndChanel($channel, $connection)
{
$channel->close();
$connection->close;
}
}
然后生产消息的代码
<?php
namespace app\api\controller;
use PhpAmqpLib\Message\AMQPMessage;
use app\api\library\RabbitMQConnection;
use think\Request;
class Test
{
public function index()
{
$Rc = new RabbitMQConnection();
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();
}
public function order()
{
$param = Request::instance()->param();
print_r($param);
}
}
然后 app\api\command 新建RabbitMq.php文件
<?php
declare (strict_types=1);
namespace app\api\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\api\library\RabbitMQConnection;
use PhpAmqpLib\Message\AMQPMessage;
class RabbitMq extends Command
{
protected function configure()
{
// 指令配置
$this->setName('Rabbitmq')
->setDescription('rabbitmq 消费队列');
}
protected function execute(Input $input, Output $output)
{
// 指令输出
$output->writeln("RabbitMQ 消费队列开始启动……\n");
$Rc = new RabbitMQConnection();
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();
}
}
}
然后去项目根目录 输入 php think
就会出现我们刚刚自定义命令行的Rabbitmq命令
这个时候我们访问刚刚我们生产消息的地方 rabbitmq里面就会出现一条数据
然后启动 rabbitmq消费者的命令
php think Rabbitmq
因为我改过Rabbitmq的端口 默认的端口 15672 用户名我也改过 根据自己的配置修改端口用户名密码即可
版权声明:本文为qq_21794099原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。