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。
对于 outbound 适配器,连接通常在发送第一个消息时建立。outbound 适配器上的 client-mode="true"
会在适配器启动时建立连接。默认情况下,适配器会自动启动。同样,连接工厂必须是类型为 client
并且有 single-use="false"
。也支持 retry-interval
和 scheduler
。如果连接失败,则会通过调度程序或在发送下一个消息时重新建立连接。
对于入站和出站,如果适配器已启动,您可以通过发送 <control-bus />
命令 @adapter_id.retryConnection()
来强制适配器建立连接。然后您可以使用 @adapter_id.isClientModeConnected()
检查当前状态。