对Symfony Messenger使用默认传输(skip amqp)

时间:2019-04-30 12:07:21

标签: symfony rabbitmq amqp

在messenger.yaml中,我将邮件相应地路由到amqp

routing:
  # Route your messages to the transports
  'App\Message\SendNewsletterMessage': amqp

但是在某些没有安装RabbitMQ的环境中,我想直接发送消息。我不想简单地注释掉这一行,因为代码已部署在多个地方。相反,我想将传输设置为内部调用(就像已被注释掉一样),但是我无法弄清楚该默认传输的名称是什么。

routing:
  # Route your messages to the transports
  'App\Message\SendNewsletterMessage':  '%env(MESSAGE_TRANSPORT)%' # amqp or...

然后我的环境变量可以是'amqp'或直接的。直接拨打电话要用什么交通工具?

2 个答案:

答案 0 :(得分:1)

看起来不可能,因为直接消息不是传输。作为解决方法,您可以重写配置:

# config/packages/dev/messenger.yaml
framework:
    messenger:
        routing: []
# config/packages/prod/messenger.yaml
framework:
    messenger:
        'App\Message\SendNewsletterMessage': amqp
# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            amqp: '%env(MESSENGER_TRANSPORT_DSN)%'

如果要为一种环境配置传输,则可以修饰messenger.senders_locator

# config/services.yaml
services:
    App\DirectSendersLocator:
        decorates: messenger.senders_locator
        arguments:
            - '@App\DirectSendersLocator.inner'
            - '%env(bool:DIRECT_TRANSPORT)%'
namespace App;

use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Sender\SendersLocatorInterface;

class DirectSendersLocator implements SendersLocatorInterface
{
    /**
     * @var SendersLocatorInterface
     */
    private $decorated;

    /**
     * @var bool
     */
    private $direct;

    public function __construct(SendersLocatorInterface $decorated, bool $direct)
    {
        $this->decorated = $decorated;
        $this->direct = $direct;
    }

    public function getSenders(Envelope $envelope, ?bool &$handle = false): iterable
    {
        if ($this->direct) {
            $handle = true;

            return [];
        }

        $this->decorated->getSenders($envelope, $handle);
    }
}

答案 1 :(得分:1)

Symfony 4.3可以处理此问题,“直接”传输称为同步:

# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            async: '%env(MESSENGER_TRANSPORT_DSN)%'
        routing:
            'App\Message\SmsNotification': async
            'App\Message\OtherMessage': async


# .env
# by default, handle this sync
MESSENGER_TRANSPORT_DSN=sync://

https://github.com/symfony/symfony/pull/30759