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()
检查当前状态。