通用入站和出站通道适配器
通道适配器是 Spring Integration 中的消息端点之一。它用于单向消息流。通道适配器有两种类型:
入站适配器 :通道的输入侧。倾听或主动阅读消息。
出站适配器 :通道的输出端。将消息发送到 Java 类或外部系统或协议。
-
源代码。
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 样式的配置文件:
<?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>
-
消息流
inAdapter
:入站通道适配器。每 1 秒调用Application$MessageProducer.produce
方法(<int:poller fixed-rate="1000"/>
)并将返回的字符串作为消息发送到通道channel
。channel
:传输消息的频道。outAdapter
:出站通道适配器。一旦消息到达通道channel
,该适配器将收到该消息,然后将其发送到Application$MessageConsumer.consume
方法,该方法在控制台上打印消息。- 因此,你可以观察到这些随机选择字符串将每隔 1 秒显示在控制台上。