spring-integration Getting started with spring-integration Generic Inbound and Outbound Channel Adapter


Example

Channel adapter is one of message endpoints in Spring Integration. It is used for unidirectional message flow. There are two types of channel adapter:

Inbound Adapter: input side of the channel. Listen or actively read message.

Outbound Adapter: output side of the channel. Send message to Java class or external system or protocol.

enter image description here

  • Source code.

    public class Application {
        static class MessageProducer {
            public String produce() {
                String[] array = {"first line!", "second line!", "third line!"};
                return array[new Random().nextInt(3)];
            }
        }
    
        static class MessageConsumer {
            public void consume(String message) {
                System.out.println(message);
            }
        }
    
        public static void main(String[] args) {
            new ClassPathXmlApplicationContext("classpath:spring/integration/stackoverflow/ioadapter/ioadapter.xml");
        }
    }
    
  • XML-style Configuration file:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:int="http://www.springframework.org/schema/integration"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd">
        <int:channel id="channel"/>
        <int:inbound-channel-adapter id="inAdapter" channel="channel" method="produce">
            <bean class="spring.integration.stackoverflow.ioadapter.Application$MessageProducer"/>
            <int:poller fixed-rate="1000"/>
        </int:inbound-channel-adapter>
        <int:outbound-channel-adapter id="outAdapter" channel="channel" method="consume">
            <bean class="spring.integration.stackoverflow.ioadapter.Application$MessageConsumer"/>
        </int:outbound-channel-adapter>
    </beans>
    
  • Message Flow

    • inAdapter: an inbound channel adapter. Invoke Application$MessageProducer.produce method every 1 second (<int:poller fixed-rate="1000"/>) and send the returned string as message to the channel channel.
    • channel: channel to transfer message.
    • outAdapter: an outbound channel adapter. Once message reached on channel channel, this adapter will receive the message and then send it to Application$MessageConsumer.consume method which print the message on the console.
    • So you can observe that these random choose string will displayed on the console every 1 second.