cmdrsharp / amqp-route-messenger
一个用于发布和监听路由交换消息的客户端。
1.2.0.1
2019-04-28 09:00 UTC
Requires
- php: >=7.2
- illuminate/support: >=5.8
- php-amqplib/php-amqplib: ^2.9.0
Requires (Dev)
- orchestra/testbench: ^3.8
- phpunit/phpunit: 8.0.*
This package is auto-updated.
Last update: 2024-09-28 21:41:22 UTC
README
一个用于发布和监听路由交换消息的客户端。
当前需求
- PHP 7.2 或更高版本
- Laravel 5.8 或更高版本
安装
通过 composer
$ composer require cmdrsharp/amqp-route-messenger
安装后,发布配置文件。
php artisan vendor:publish --provider="CmdrSharp\AmqpRouteMessenger\AmqpRouteMessengerServiceProvider"
这将创建一个位于您的 Laravel 配置目录中的 amqproutemessenger.php
文件。该文件将包含 RabbitMQ 队列详情的绑定。建议您将这些绑定直接定义在 .env
文件中。配置文件将自动读取这些值。
RABBITMQ_HOST=
RABBITMQ_PORT=5672
RABBITMQ_VHOST=/
RABBITMQ_LOGIN=
RABBITMQ_PASSWORD=
对于 SSL 连接,只需在您的 .env 文件中指定 CA 证书的路径以及是否使用对等验证。如果指定了这些值,将建立一个 AMQPSSLConnection
。
RABBITMQ_CA_FILE="/path/to/yourca.crt"
RABBITMQ_VERIFY_PEER=true
使用方法
将协议注入到需要客户端的类中
/** * @var ClientInterface */ protected $client; /** * @param ClientInterface $client */ public function __construct(ClientInterface $client) { $this->client = $client; }
或者,如果您不想自动加载,您也可以直接要求它。
use CmdrSharp\AmqpRouteMessenger\Client; /** * @var ClientInterface */ protected $client; public function __construct() { $this->client = new Client(); }
示例:使用关联 ID 发布消息
我们在这里所做的只是声明将消息发布到哪个交换机,然后使用指定的关联 ID 发布消息。 declareExchange
接受一个可选的第二个参数,这使得它成为 passive
$instance = $this->client->declareExchange('messages')->publish('correlation_id', 'your message'); // Don't forget to close the channel and connection when done! $instance->closeChannel()->closeConnection();
示例:使用关联 ID 读取消息
建议在发布任何消息之前设置消费者。这是为了确保已经创建了队列绑定,以便正确路由发布的消息。
$instance = $this->client->declareExchange('messages') ->declareQueue() ->bindQueue('correlation_id'); // Note: Reading does freeze the thread until it receives a message. $message = $instance->read(); // Again, don't forget to close the channel and connection! $instance->closeChannel()->closeConnection();
示例:读取和发布结合使用
$instance = $this->client->declareExchange('messages') ->declareQueue() ->bindQueue('correlation_id'); $instance->publish('correlation_id', 'your message'); $message = $instance->read(10); // Optional timeout in seconds. $instance->closeChannel()->closeConnection();
版本
此包遵循 显式版本。