How to avoid Symfony Messenger wrapping the message into an object with a message key?

61 Views Asked by At

I am using Symfony Messenger 6.3 (with Symfony 6.3) to publish a message on a RabbitMQ exchange. The problem is that Symfony Messenger automatically wraps my message into a message object which has a message key.

For example, if I send a message with [ 'id' => 1, 'intensity' => 2], the message that will appears in my queue will be looks like { message: { id: 1, intensity: 2 } } but I would like to only have my message content into the queue as { id: 1, intensity: 2 } (without the message key).

How can I achieve that please ?

config/packages/messenger.yaml

framework:
    messenger:

        serializer:
            default_serializer: messenger.transport.symfony_serializer
            symfony_serializer:
                format: json
                context: { }

        transports:
            # https://symfony.com/doc/current/messenger.html#transport-configuration
            sensor:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                options:
                    exchange:
                        type: 'topic'
                        name: 'sensor.exchange'

        routing:
            # Route your messages to the transports
            'App\Message\SensorMessage': sensor

AbstractMessage.php

<?php

namespace App\Message;

class AbstractMessage implements MessageInterface
{
    protected array $message;

    public function __construct(array $message)
    {
        $this->message = $message;
    }

    public function getMessage(): array
    {
        return $this->message;
    }
}

MessageInterface.php

<?php

namespace App\Message;

interface MessageInterface
{
    public function getMessage(): array;
}

SensorMessage.php

<?php

namespace App\Message;

class SensorMessage extends AbstractMessage
{
    public function __construct(array $message)
    {
        parent::__construct($message);
    }
}

MessageService.php

<?php

namespace App\Service;

use App\Message\MessageInterface;
use Symfony\Component\Messenger\Bridge\Amqp\Transport\AmqpStamp;
use Symfony\Component\Messenger\MessageBusInterface;

class MessageService
{
    private MessageBusInterface $messageBus;

    public function __construct(MessageBusInterface $messageBus)
    {
        $this->messageBus = $messageBus;
    }

    public function sendAMQPMessage(string $routingKey, MessageInterface $message): void
    {
        $this->messageBus->dispatch($message, [new AmqpStamp($routingKey)]);
    }
}

And my publish method :

private function publishSensorMessage(Sensor $sensor): void
    {
        $message = new SensorMessage([ 'id' => $sensor->getId(), 'intensity' => $sensor->getIntensity()]);

        $this->messageService->sendAMQPMessage('*', $message);
    }
0

There are 0 best solutions below