15.5.13

Asynchronous Gateway and Parallel DirectChannel

Parallel DirectChannel

DirectChannel could work in a Parallel way:

<int:channel id="channel-in">
<int:dispatcher load-balancer="round-robin" task-executor="taskExec"/>
</int:channel>
However, a channel with a dispatcher doesn't necessary be handled in parallel. In the above example, if the Gateway expects some return, DirectChannel won't returned immediately after execute the job in another executor. Although the execution is driven into another thread, but the current thread will be blocked for the reply:

MessagingTemplate:

private <S, R> Message<R> doSendAndReceive(MessageChannel channel, Message<S> requestMessage) {
Object originalReplyChannelHeader = requestMessage.getHeaders().getReplyChannel();
Object originalErrorChannelHeader = requestMessage.getHeaders().getErrorChannel();
TemporaryReplyChannel replyChannel = new TemporaryReplyChannel(this.receiveTimeout);
requestMessage = MessageBuilder.fromMessage(requestMessage)
.setReplyChannel(replyChannel)
.setErrorChannel(replyChannel)
.build();
this.doSend(channel, requestMessage);
Message<R> reply = this.doReceive(replyChannel);
if (reply != null) {
reply = MessageBuilder.fromMessage(reply)
.setHeader(MessageHeaders.REPLY_CHANNEL, originalReplyChannelHeader)
.setHeader(MessageHeaders.ERROR_CHANNEL, originalErrorChannelHeader)
.build();
}
return reply;
}

The doReceived(...) method will blocked the caller's thread until it receives the reply from the replyChannel, which technically makes the work in sync.
If you really want to have some reply from the DirectChannel while you want to have it work in parallel, you need Asynchronous Gateway or something similar.

Asynchronous Gateway

You can of course use the default asynchronous executor, which is AsyncTaskExecutor. But the default executor will create as many threads as it can to run the Gateway. Sometimes it will drain the resources of your system without proper control. So you might want to manually set up an executor with some control.




No comments: