|
如需使用最新稳定版本,请使用 Spring Integration 7.0.4! |
TCP 适配器
提供使用前述提到的连接工厂的 TCP 入站和出站通道适配器。
这些适配器有两个相关属性:connection-factory 和channel。
connection-factory 属性指示用于管理适配器连接的连接工厂。
channel 属性指定消息到达出站适配器的通道,以及入站适配器放置消息的通道。
虽然入站和出站适配器可以共享一个连接工厂,但服务器连接工厂始终由入站适配器“拥有”;客户端连接工厂始终由出站适配器“拥有”。
每种类型的适配器只能有一个获取对连接工厂的引用。
以下示例展示了如何定义客户端和服务器 TCP 连接工厂:
<bean id="javaSerializer"
class="org.springframework.core.serializer.DefaultSerializer"/>
<bean id="javaDeserializer"
class="org.springframework.core.serializer.DefaultDeserializer"/>
<int-ip:tcp-connection-factory id="server"
type="server"
port="1234"
deserializer="javaDeserializer"
serializer="javaSerializer"
using-nio="true"
single-use="true"/>
<int-ip:tcp-connection-factory id="client"
type="client"
host="localhost"
port="#{server.port}"
single-use="true"
so-timeout="10000"
deserializer="javaDeserializer"
serializer="javaSerializer"/>
<int:channel id="input" />
<int:channel id="replies">
<int:queue/>
</int:channel>
<int-ip:tcp-outbound-channel-adapter id="outboundClient"
channel="input"
connection-factory="client"/>
<int-ip:tcp-inbound-channel-adapter id="inboundClient"
channel="replies"
connection-factory="client"/>
<int-ip:tcp-inbound-channel-adapter id="inboundServer"
channel="loop"
connection-factory="server"/>
<int-ip:tcp-outbound-channel-adapter id="outboundServer"
channel="loop"
connection-factory="server"/>
<int:channel id="loop"/>
另请参阅 基于注解的配置 和 使用 Java DSL 进行 TCP 组件开发。
在前面的配置中,到达input通道的消息通过由client连接工厂创建的连接进行序列化,在服务器端接收后,被放置到loop通道上。
由于loop是outboundServer的输入通道,该消息会沿同一连接循环返回,由inboundClient接收并存入replies通道。
传输过程中使用的是 Java 序列化。
通常,入站适配器使用一个type="server"连接工厂来监听传入的连接请求。
在某些情况下,您可能希望以相反的方式建立连接,即入站适配器连接到外部服务器,然后在该连接上等待传入消息。
通过在内向适配器上设置 client-mode="true" 可支持此拓扑结构。
在此情况下,连接工厂的类型必须为 client,且必须将 single-use 设置为 false。
两个额外的属性支持此机制。
retry-interval指定(以毫秒为单位)在连接失败后框架尝试重新连接的频率。
scheduler提供一个TaskScheduler来调度连接尝试并测试连接是否仍然活跃。
如果您未提供调度器,框架将使用默认的 taskScheduler Bean。
对于出站适配器,连接通常在发送第一条消息时建立。
出站适配器上的 client-mode="true" 会导致在适配器启动时建立连接。
默认情况下,适配器会自动启动。
同样,连接工厂必须是类型为 client 且具备 single-use="false" 的工厂。
也支持 retry-interval 和 scheduler。
如果连接失败,将由调度器或在下一次发送消息时重新建立。
对于入站和出站,如果适配器已启动,您可以通过发送<control-bus />命令来强制适配器建立连接:@adapter_id.retryConnection()。
然后您可以使用@adapter_id.isClientModeConnected()检查当前状态。