通用入站和出站通道介面卡
通道介面卡是 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 秒顯示在控制檯上。