Message Contexts
Message context provides a way to propagate data along the processing of a message. It can be used to propagate message specific objects in an implicit manner and be able to retrieve them later, such as the user, session or transaction.
Important
Message contexts are only support by Kafka, AMQP, RabbitMQ and MQTT connectors.
Note
Message context support is an experimental and SmallRye only feature.
What's a message context
A message context is execution context on which a message is processed.
Each stage of the processing is going to use the same execution context.
Thus, it allows storing data which can later be restored.
For example, you can imagine storing some authentication (User
in the following example) data in one part of your processing and restore it in a later stage.
Uni
or CompletionStage
)
The difference with metadata
Message metadata can be used to provide a similar feature.
However, it requires using Messages
which can be inconvenient (need to handle the acknowledgement manually).
Message Contexts provide a simpler API, closer to a Message CDI scope: you can save data, and restore it later.
The implicit propagation avoid having to deal with Messages
.
Supported signatures
Message context works with:
- methods consuming or producing
Messages
,Uni<Message<T>>
andCompletionStage<Message<T>>
- methods consuming or producing payloads,
Uni<Payload>
andCompletionStage<Payload>
. - blocking and non-blocking methods
However, message context are NOT enforced when using methods consuming or producing:
Multi
,Flow.Publisher
,Publisher
andPublisherBuilder
Subscriber
,Flow.Subscriber
, andSubscriberBuilder
Processor
,Flow.Processor
, andProcessorBuilder
Under the hood
Under the hood, the message context feature uses Vert.x duplicated contexts. A duplicated context is a view of the "root" (event loop) context, which is restored at each stage of the message processing.
Each time that a compatible connector receives a message from a broker, it creates a new duplicated context and attaches it to the message. So the context is stored in the metadata of the message.
When the message is processed, SmallRye Reactive Messaging makes sure that this processing is executed on the stored duplicated context.