php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)

php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)

  • 序言
  • 操作环境
  • tp6设置
    • 开启多应用(按需开启)
    • 完善多应用(按需添加文件夹)
    • 自定义命令
      • 命令文件代码
    • rabbitMQ配置
  • 最终目录结构
  • 生产者代码
  • 消费者代码
  • 调用者代码
  • 运行示例

序言

emmmmmmm~~~,通过前六章相信你对php操作RabbitMQ有了一定的掌握,在这一章将使用ThinkPHP6实战。

操作环境

  1. php7.3与apache
    php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)_第1张图片
  2. 框架为tp6
    php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)_第2张图片

tp6设置

开启多应用(按需开启)

composer require topthink/think-multi-app
php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)_第3张图片

完善多应用(按需添加文件夹)

php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)_第4张图片

自定义命令

  1. 使用命令生成自定义命令文件
    在这里插入图片描述

命令文件代码

<?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 app\common\controller\MqConsumer;

class Order extends Command
{
     
    protected function configure()
    {
     
        // 指令配置
        $this->setName('order')
            ->setDescription('the order command');
    }

    protected function execute(Input $input, Output $output)
    {
     
        // 指令输出
        $consumer = new MqConsumer();
        $consumer->consumer('order');
    }
}

<?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 app\common\controller\MqConsumer;

class Goods extends Command
{
     
    protected function configure()
    {
     
        // 指令配置
        $this->setName('goods')
            ->setDescription('the goods command');
    }

    protected function execute(Input $input, Output $output)
    {
     
        $consumer = new MqConsumer();
        $consumer->consumer('goods');
    }
}

  1. 在根目录config文件夹下的console.php文件中注册命令。
    php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)_第5张图片
<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
    // 指令定义
    'commands' => [
    	'order' => 'app\command\order',
    	'goods' => 'app\command\goods'
    ],
];

rabbitMQ配置

在根目录config文件夹下新建rabbitmq.php文件。

<?php 
// +----------------------------------------------------------------------
// | rabbitMQ 示例配置
// +----------------------------------------------------------------------

return [

	// 连接信息
	'AMQP' => [
		'host'     => '127.0.0.1',
		'port'     => '5672',
		'username' => 'guest',
		'password' => 'guest',
		'vhost'    => '/' 
	],

	//topic队列  
	'topic_queue' => [
		'exchange_name' => 'topic_exchange',
		'exchange_type' => 'topic',
		'queue_name'    => 'topic_queue',
		'route_key'     => '',
		'consumer_tag'  => 'topic'
	], 

	//商品队列 
	'goods_queue' => [
		'exchange_name' => 'topic_exchange',
		'exchange_type' => 'topic',
		'queue_name'    => 'goods_queue',
		'route_key'     => '*.goods',
		'consumer_tag'  => 'goods'
	], 

	//订单队列 
	'order_queue' => [
		'exchange_name' => 'topic_exchange',
		'exchange_type' => 'topic',
		'queue_name'    => 'order_queue',
		'route_key'     => '*.order',
		'consumer_tag'  => 'order'
	], 


	//...等等队列
];

最终目录结构

php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)_第6张图片

生产者代码

<?php
namespace app\common\controller;

use think\facade\Config;
use think\facade\Log;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;


class MqProducer
{
     
    public function publish($data, $key)
    {
     
    	//获取配置
        $amqp = Config::get('rabbitmq.AMQP');
        $amqpDefail = Config::get('rabbitmq.topic_queue');

        //连接
        $connection = new AMQPStreamConnection(
        	$amqp['host'], 
        	$amqp['port'], 
        	$amqp['username'], 
        	$amqp['password']
        );

        //建立通道
        $channel = $connection->channel();

        //初始化交换机  
        $channel->exchange_declare($amqpDefail['exchange_name'], $amqpDefail['exchange_type'], false, true, false); 
        
        //生成消息
		$msg = new AMQPMessage(json_encode($data), [
			'content-type'  => 'application/json',
			'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT
		]);

		//推送消息到某个交换机
		
		$channel->basic_publish($msg, $amqpDefail['exchange_name'], $key);

		$channel->close();
		$connection->close();

		echo 'send';
    }

}

消费者代码

<?php
namespace app\common\controller;

use think\facade\Config;
use think\facade\Log;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;

class MqConsumer
{
     
	/**
	 * 消费者
	 */
	public function consumer($name)
    {
     
    	//获取配置
        $amqp = Config::get('rabbitmq.AMQP');
        $amqpDefail = Config::get('rabbitmq.'.$name.'_queue');

        //连接
        $connection = new AMQPStreamConnection(
        	$amqp['host'], 
        	$amqp['port'], 
        	$amqp['username'], 
        	$amqp['password']
        );

        //建立通道
        $channel = $connection->channel();

        //流量控制
        $channel->basic_qos(null, 1, null);

        //初始化交换机  
        $channel->exchange_declare($amqpDefail['exchange_name'], $amqpDefail['exchange_type'], false, true, false); 

        //初始化队列
        $channel->queue_declare($amqpDefail['queue_name'], false, true, false, false);

        //绑定队列与交换机
        $channel->queue_bind($amqpDefail['queue_name'], $amqpDefail['exchange_name'], $amqpDefail['route_key']);

        //消费消息
        $channel->basic_consume($amqpDefail['queue_name'], $amqpDefail['consumer_tag'], false, false, false, false, [$this, 'msgProc']);

        //退出
        register_shutdown_function([$this, 'shutdown'], $channel, $connection);
        
        //监听
        while(count($channel->callbacks)) {
     
		    $channel->wait();
		}
    }

	/**
	 * 消息处理
	 * @param  $msg
	 */
	public function msgProc($msg)
    {
     
    	echo $msg->body."\n";
    	$msg->ack();
    }

    /**
     * 退出
     * @param  $channel [信道]
     * @param $connection [连接]
     */
    public function shutdown($channel, $connection)
    {
     
		$channel->close();
		$connection->close();
    }

}

调用者代码

<?php
namespace app\index\controller;

use app\BaseController;
use app\common\controller\MqProducer;

class Index extends BaseController
{
     
    public function index()
    {
     
    	$data = ['id'=>rand(1,100), 'msg'=>'lalala'];
        $producer = new MqProducer();
        $producer->publish($data, 'all.order');

    }

     public function index2()
    {
     
    	$data = ['id'=>rand(1,100), 'msg'=>'lalala'];
        $producer = new MqProducer();
        $producer->publish($data, 'all.goods');

    }
}

运行示例

php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)_第7张图片
php实战RabbitMQ八(ThinkPHP6应用RabbitMQ)_第8张图片

你可能感兴趣的:(php,rabbitmq)