跳到主要内容
版本:7.0.2

TCP 连接拦截器

DeepSeek V3 中英对照 TCP Connection Interceptors

你可以通过引用 TcpConnectionInterceptorFactoryChain 来配置连接工厂。你可以使用拦截器为连接添加行为,例如协商、安全和其他选项。框架目前没有提供任何拦截器,但可以参考源代码仓库中的 InterceptedSharedConnectionTests 作为示例。

测试用例中使用的 HelloWorldInterceptor 工作方式如下:

拦截器首先配置了一个客户端连接工厂。当第一条消息通过被拦截的连接发送时,拦截器会通过该连接发送"Hello",并期望收到"world!"作为响应。当这一过程完成后,协商即告完成,原始消息将被发送。此外,使用同一连接发送的后续消息无需进行额外的协商。

当配置了服务器连接工厂时,拦截器要求第一条消息必须是'Hello',如果是,则返回'world!'。否则,它会抛出一个异常,导致连接被关闭。

所有 TcpConnection 方法均会被拦截。拦截器实例通过拦截器工厂为每个连接创建。若拦截器具有状态,工厂应为每个连接创建新实例;若无状态,则同一拦截器可包装每个连接。拦截器工厂需添加至拦截器工厂链的配置中,您可通过设置 interceptor-factory 属性将其提供给连接工厂。拦截器必须继承 TcpConnectionInterceptorSupport,工厂必须实现 TcpConnectionInterceptorFactory 接口。TcpConnectionInterceptorSupport 包含直通方法,通过继承此类,您仅需实现希望拦截的方法。

以下示例展示了如何配置连接拦截器工厂链:

<bean id="helloWorldInterceptorFactory"
class="o.s.i.ip.tcp.connection.TcpConnectionInterceptorFactoryChain">
<property name="interceptors">
<array>
<bean class="o.s.i.ip.tcp.connection.HelloWorldInterceptorFactory"/>
</array>
</property>
</bean>

<int-ip:tcp-connection-factory id="server"
type="server"
port="12345"
using-nio="true"
single-use="true"
interceptor-factory-chain="helloWorldInterceptorFactory"/>

<int-ip:tcp-connection-factory id="client"
type="client"
host="localhost"
port="12345"
single-use="true"
so-timeout="100000"
using-nio="true"
interceptor-factory-chain="helloWorldInterceptorFactory"/>