imatic/notification

用于在应用程序之间发送可靠消息的简单库

v1.4.0 2023-05-09 10:22 UTC

This package is auto-updated.

Last update: 2024-09-09 13:27:21 UTC


README

Build Status
License: MIT

Imatic Notification

简化使用消息队列的应用程序

配置

库需要您指定2个配置选项。如何指定它们取决于您的服务容器(请参阅访问服务部分)。

  • imatic_notification_params
    • 连接到代理的参数
<?php
$params = [
    'host' => 'localhost',
    'port' => 5672,
    'user' => 'guest',
    'password' => 'guest',
    'namespace' => '',
];
  • imatic_notification.logger
    • 实现 psr log 接口的日志记录器
    • 在下面的示例中,我们使用了 NullLogger,它不会记录任何内容 - 我们强烈建议不要在生产环境中使用此日志记录器,因为如果发生错误,您将无法了解错误原因

库接口

您将使用2个接口:Publisher,用于将消息发布到队列,以及Consumer,用于消费发布者发布的消息。

<?php
namespace Imatic\Notification;

interface Connection
{
   public function createPublisher(ChannelParams $params);

   public function createConsumer(ChannelParams $params);
}

interface Publisher
{
    public function publish(Message $message, $key = '');
}

interface Consumer
{
    public function consume($queueName, $key, callable $callback);

    public function wait();

    public function waitN($n);
}

这两个接口由服务 imatic_notification.connection 实现

访问服务

建议使用一个容器从定义文件 "config/services.yml" 创建连接对象。以下展示了多种可能的方法之一。

使用 Symfony

要加载 Symfony 的服务,您需要编辑您的 app/config/config.yml 文件。

imports:
    - { resource: ../../vendor/imatic/notification/config/services.yml }

parameters:
    imatic_notification_params: []

services:
    imatic_notification.logger:
        class: Psr\Log\NullLogger

然后您可以从 Symfony 容器中访问服务。

<?php
$connection = $this->container->get('imatic_notification.connection');

使用示例

<?php
// create connection to the broker
$connection = $this->container->get('imatic_notification.connection');

// create channel parameters
$channelParams = new ChannelParams($exchange = 'imatic_queue_test');

// create consumer
$consumer = $connection->createConsumer($channelParams);

// listen to the messages on queue "queue_name"
// to all messages having routing key "routing_key"
$consumer->consume('queue_name', 'routing_key', function (Message $msg) {
    $this->logger->logData('data');

    // you need to return true to tell the broker that it can discard the messaga
    // because you successfully processed it
    return true;
});

// create publisher
$publisher = $connection->createPublisher($channelParams);

// publish message to the channel with routing key "routing_key"
$publisher->publish(new Message(['data' => 'bdy']), 'routing_key');

// consume only 1 message, then continue
$consumer->waitN(1);

// won't return till you have listening consumers
$consumer->wait();