thinkphp5.1 MQ 生产者

thinkphp5.1 MQ 生产者

composer require riges/php-rabbitmqlib
<?php


namespace app\common\service;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use think\facade\Env;

class FrsMq
{
    const exchange = 'abc';
    const routingKey = 'bcd';
    public static function pushMessage($data)
    {
        try {
            //new 一个MQ连接对象
            $connection = new AMQPStreamConnection(Env::get('AMQP_FRS_HOST','127.0.0.1',false), Env::get('AMQP_FRS_PORT',5672,false),  Env::get('AMQP_FRS_USER','guest',false),  Env::get('AMQP_FRS_PASSWORD','',false), Env::get('AMQP_FRS_VHOST','/',false));
            //获取一个通道对象,如果不存在则创建
            $channel = $connection->channel();
            //申明一个交换器,交换器名称,类型,,是否持久化,是否自动删除
            $channel->exchange_declare(self::exchange, 'topic', false, true, false);
            $messageBody = $data;
            $message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
            //发送一条消息,消息内容,交换器,routing_key
            $channel->basic_publish($message, self::exchange,self::routingKey);
            //关闭通道
            $channel->close();
            //关闭MQ连接
            $connection->close();
            return "ok";
        }catch (\Exception | \Throwable $exception){
            return $exception->getMessage();
        }
    }
}


回复列表



回复操作

正在加载验证码......

请先拖动验证码到相应位置

发布时间:2021-07-19 19:23:18

修改时间:2021-07-19 19:25:17

查看次数:265

评论次数:0