Whereas the MessageHandler
interface provides the foundation for many of the
components that enable non-invasive invocation of your application code from the messaging
system, sometimes it is necessary to invoke the messaging system from your application
code. Spring Integration provides a MessageExchangeTemplate
that supports a
variety of message-exchanges, including request/reply scenarios. For example, it is possible to send a request
and wait for a reply.
MessageExchangeTemplate template = new MessageExchangeTemplate(); Message reply = template.sendAndReceive(new StringMessage("test"), someChannel);
In that example, a temporary anonymous channel would be created internally by the template. The 'sendTimeout' and 'receiveTimeout' properties may also be set on the template, and other exchange types are also supported.
public boolean send(final Message<?> message, final MessageTarget target) { ... } public Message<?> sendAndReceive(final Message<?> request, final MessageTarget target) { .. } public Message<?> receive(final PollableSource<?> source) { ... } public boolean receiveAndForward(final PollableSource<?> source, final MessageTarget target) { ... }
Additionally, a 'transactionManager' can be configured on a MessageExchangeTemplate as well as the various transaction attributes:
template.setTransactionManager(transactionManager); template.setPropagationBehaviorName(propagationBehavior); template.setIsolationLevelName(isolationLevel); template.setTransactionTimeout(transactionTimeout); template.setTransactionReadOnly(readOnly); template.setReceiveTimeout(receiveTimeout); template.setSendTimeout(sendTimeout);
Finally, there is a also an asynchronous version called AsyncMessageExchangeTemplate
whose constructor accepts a TaskExecutor
, and whose Message-returning methods
return an AsyncMessage
. That is essentially a wrapper for any Message that also
implements Future<Message<T>>
:
AsyncMessageExchangeTemplate template = new AsyncMessageExchangeTemplate(taskExecutor); Message reply = template.sendAndReceive(new StringMessage("test"), someChannel); // do some work in the meantime reply.getPayload(); // blocks if still waiting for actual reply