Search code examples
symfonyrabbitmqsymfony4messenger

Dispatch message to different transport or vhost in Symfony 4 & Messenger


I need to dispatch message depending on parameter "host" in the message to different vhost/transport. Is it possible to do it in standard Messenger component for Symfony 4.* ? I have workers on each server and all workers connecting to concrete vhost.

framework:
    messenger:
        serializer:
            default_serializer: messenger.transport.symfony_serializer
            symfony_serializer:
                format: json
                context: { }
        transports:
            wendy:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%/server-wendy'
                options:
                    exchange:
                        name: wendy
                        type: direct
                    queues:
                        virtual_hosts:
                            durable: 1
                            binding_keys: ['virtual_hosts']
                        ftp:
                            durable: 1
                            binding_keys: ['ftp']
            stan:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%/server-stan'
                options:
                    exchange:
                        name: stan
                        type: direct
                    queues:
                        virtual_hosts:
                            durable: 1
                            binding_keys: ['virtual_hosts']
                        ftp:
                            durable: 1
                            binding_keys: ['ftp']

        routing:
            # Route your messages to the transports
            'App\Message\VirtualHostNotification': [wendy, stan]

For example:

$this->messageBus->dispatch(
    new VirtualHostNotification($virtualHost),
    [new AmqpStamp('wendy.virtual_hosts', AMQP_NOPARAM)],
    $transport,
    $vhost
);

Solution

  • add the "vhost" variable. for example :

                wendy:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%/server-wendy'
                options:
                    vhost: '%env(MESSENGER_TRANSPORT_VHOST)%'
                    exchange:
                        name: wendy
                        type: direct
                    queues:
                        virtual_hosts:
                            durable: 1
                            binding_keys: ['virtual_hosts']
                        ftp:
                            durable: 1
                            binding_keys: ['ftp']