Norway



Samuel Roze  - 3397cc9d55eb953351c84ed40e9425a7 - New in Symfony 4.1: Messenger component (Symfony Blog)

In Symfony 4.1, we added a new Messenger component that helps applications
send and receive messages to/from other applications or via message queues. It
provides a message bus and some routing capabilities to send messages in any
service where you need it, like in a controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9

11

13
14
15
16
17
18
19
// src/Controller/DefaultController.php
namespace AppController;

use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentMessengerMessageBusInterface;
use SymfonyComponentRoutingAnnotationRoute;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function index(MessageBusInterface $bus)
    {
        // ...

        $bus->dispatch(new MyMessage());
    }
}

Sending messages is the first part of the process. Then you need to create a
“message handler” and register it as a service with the .message_handler
tag to receive the message and do something with it:

// src/MessageHandler/MyMessageHandler.php
namespace AppMessageHandler;

class MyMessageHandler
{
    public function __invoke(MyMessage $message)
    {
        // do something with the message
    }
}

The includes an AMQP adapter to communicate with most of the
popular AMQP brokers, such as RabbitMQ. The communication with queuing systems
or third parties (Kafka, Amazon SQL, Google Pub/sub) is delegated to libraries
like Enqueue’s adapter:

# config/packages/messenger.yaml
framework:
    messenger:
        adapters:
            default: "amqp://guest:guest@localhost:5672/%2f/messages"

This config allows to route messages to the messenger.default_adapter and
also configures a messenger.default_sender and messenger.default_receiver
to be used when routing and consuming messages.

Instead of calling a handler, you can also route your messages to one or
multiple senders:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# config/packages/messenger.yaml
framework:
    messenger:
        routing:
            # route this message to a singe sender
            'MyMessageMessage':  messenger.default_sender

            # route this message to multiple senders
            'MyMessageToBeSentToTwoSenders': [messenger.default_sender, messenger.audit_sender]

            # route the  of messages to the default sender
            '*': messenger.default_sender

Once your messages have been routed, you can consume them with the
messenger:consume-messages command:

$ bin/console messenger:consume-messages messenger.default_receiver

The message bus defined by the Messenger component is based on middlewares. You
can read more about them and the rest of features of Messenger in the latest
draft of its documentation.



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here