@@ -2135,6 +2135,71 @@ That's it! You can now consume each transport:
21352135 If a handler does *not * have ``from_transport `` config, it will be executed
21362136 on *every * transport that the message is received from.
21372137
2138+ Process Messages by Batches
2139+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
2140+
2141+ You can declare "special" handlers which will process messages by batch.
2142+ By doing so, the handler will wait for a certain amount of messages to be
2143+ pending before processing them. The declaration of a batch handler is done
2144+ by implementing
2145+ :class: `Symfony\\ Component\\ Messenger\\ Handler\\ BatchHandlerInterface `. The
2146+ :class: `Symfony\\ Component\\ Messenger\\ Handler\\ BatchHandlerTrait ` is also
2147+ provided in order to ease the declaration of these special handlers::
2148+
2149+ use Symfony\Component\Messenger\Handler\Acknowledger;
2150+ use Symfony\Component\Messenger\Handler\BatchHandlerInterface;
2151+ use Symfony\Component\Messenger\Handler\BatchHandlerTrait;
2152+
2153+ class MyBatchHandler implements BatchHandlerInterface
2154+ {
2155+ use BatchHandlerTrait;
2156+
2157+ public function __invoke(MyMessage $message, Acknowledger $ack = null)
2158+ {
2159+ return $this->handle($message, $ack);
2160+ }
2161+
2162+ private function process(array $jobs): void
2163+ {
2164+ foreach ($jobs as [$message, $ack]) {
2165+ try {
2166+ // Compute $result from $message...
2167+
2168+ // Acknowledge the processing of the message
2169+ $ack->ack($result);
2170+ } catch (\Throwable $e) {
2171+ $ack->nack($e);
2172+ }
2173+ }
2174+ }
2175+
2176+ // Optionally, you can redefine the `shouldFlush()` method
2177+ // of the trait to define your own batch size
2178+ private function shouldFlush(): bool
2179+ {
2180+ return 100 <= \count($this->jobs);
2181+ }
2182+ }
2183+
2184+ .. note ::
2185+
2186+ When the ``$ack `` argument of ``__invoke() `` is ``null ``, the message is
2187+ expected to be handled synchronously. Otherwise, ``__invoke() `` is
2188+ expected to return the number of pending messages. The
2189+ :class: `Symfony\\ Component\\ Messenger\\ Handler\\ BatchHandlerTrait ` handles
2190+ this for you.
2191+
2192+ .. note ::
2193+
2194+ By default, pending batches are flushed when the worker is idle as well
2195+ as when it is stopped.
2196+
2197+ .. versionadded :: 5.4
2198+
2199+ :class: `Symfony\\ Component\\ Messenger\\ Handler\\ BatchHandlerInterface ` and
2200+ :class: `Symfony\\ Component\\ Messenger\\ Handler\\ BatchHandlerTrait ` were
2201+ introduced in Symfony 5.4.
2202+
21382203Extending Messenger
21392204-------------------
21402205
0 commit comments