devyk / yii2-amqp
Yii 2 扩展包装器,用于通过 AMQP 与 RabbitMQ 服务器通信。基于 videlalvaro/php-amqplib。
v1.0.5
2017-05-22 14:23 UTC
Requires
- php: >=5.3.0
- php-amqplib/php-amqplib: ~2.0
- webtoucher/yii2-commands: *
- yiisoft/yii2: 2.0.*
This package is not auto-updated.
Last update: 2024-09-21 10:56:12 UTC
README
AMQP 扩展包装器,用于与 RabbitMQ 服务器通信。基于 php-amqplib/php-amqplib。此分支提供了一个参数列表的替代方案,以便一个工作进程可以监听多个队列。
安装
安装此扩展的首选方式是通过 composer。
将以下行
...
"repositories":[
{
"type":"git",
"url":"https://github.com/M0nsterLabs/yii2-migration-aware-module"
},
],
...
"devyk/yii2-amqp": "1.0.2"
添加到您的 composer.json
文件中。
在控制台配置中添加以下内容
return [ ... 'components' => [ ... 'amqp' => [ 'class' => 'devyk\amqp\components\Amqp', 'host' => '127.0.0.1', 'port' => 5672, 'user' => 'your_login', 'password' => 'your_password', 'vhost' => '/', ], ... ], ... 'controllerMap' => [ ... 'rabbit' => [ 'class' => 'devyk\amqp\controllers\AmqpListenerController', 'interpreters' => [ 'my-exchange' => 'app\components\RabbitInterpreter', // interpreters for each exchange ], ], ... ], ... ];
添加消息解释器类 @app/components/RabbitInterpreter
与您为不同路由键的处理程序
<?php namespace app\components; use devyk\amqp\components\AmqpInterpreter; use app\services\ExampleServiceInterface; class RabbitInterpreter extends AmqpInterpreter { protected $service; /** * Example of passing custom service as dependency for the AmqpInterpreter */ public function __construct(ExampleServiceInterface $exampleService) { $this->service = $exampleService; parent::__construct(); } /** * Interprets AMQP message with routing key 'hello_world'. * * @param array $message */ public function readHelloWorld($message) { // todo: write message handler $this->log(print_r($message, true)); } }
用法
只需运行命令
$ php yii rabbit
以在指定的交换机上监听队列
$ php yii rabbit <queue_name> --exchange=<exchange_name>
以一个工作进程监听多个队列
$ php yii rabbit <queue_name>, <queue_name_1> --exchange=<exchange_name>
以启用自动确认
$ php yii rabbit <queue_name>, <queue_name_1> --noAck=true
您还可以为您的需求创建控制器。只需使用类 devyk\amqp\controllers\AmqpConsoleController
替代 yii\web\Controller
作为您的 Web 控制器,并使用类 devyk\amqp\controllers\AmqpConsoleController
替代 yii\console\Controller
作为您的控制台控制器。AMQP 连接将通过属性 connection
提供。AMQP 通道将通过属性 channel
提供。