- Spring Integration Essentials
- Chandan Pandey
- 317字
- 2025-02-26 20:04:11
Spring implementation of channels
Spring Integration defines a top-level interface for the message channel that should be implemented by any of the concrete channel implementations, as shown here:
public interface MessageChannel { boolean send(Message<?> message); boolean send(Message<?> message, long timeout); }
The MessageChannel
interface defines two versions of the send
method—one which accepts only Message
as an argument while the other one accepts an additional parameter (timeout
). The send
method returns true if the message is sent out successfully; otherwise, if it times out or the sending fails for some reason, it returns false.
Further, Spring Integration provides a sub type of the MessageChannel
interface to support two types of channels: PollableChannel
and SubscribableChannel
. This is explained in more detail in the following points:
- Pollable channel: This channel provides the interface that has two versions of receive, one which does not take any argument and the other which provides an option to specify the
timeout
parameter. The following code snippet is the interface declaration:public interface PollableChannel extends MessageChannel { Message<?> receive(); Message<?> receive(long timeout); }
- Subscribeable channel: This interface exposes methods to subscribe and unsubscribe from the channel. The following code snippet is the interface declaration for a subscribe-able channel:
public interface SubscribableChannel extends MessageChannel { boolean subscribe(MessageHandler handler); boolean unsubscribe(MessageHandler handler); }
An instance of the MessageHandler
interface is passed as an argument to the subscribe
and unsubscribe
methods. The MessageHandler
interface exposes only one method, handleMessage
, to handle the message:
public interface MessageHandler { void handleMessage(Message<?> message) throws MessageException; }
Whenever a message arrives on a channel, an implementation of the message handler is looked upon by the framework, and the message is passed to the implementer's handleMessage
method.
Although Spring Integration defines message channel interfaces and allows users to provide their implementation, it's hardly ever needed. Spring Integration has provided many implementations of channels that can be used off the shelf.