【发布时间】:2018-04-05 16:59:30
【问题描述】:
我有一个使用 spring 集成 TCP 构建的 TCP 客户端,服务器支持保持活动消息(ping/pong 样式)。连接是使用CachingClientConnectionFactory 配置的,我想利用此服务器功能。这是我的 bean 配置:
private static final int SERIALIZER_HEADER_SIZE = 2;
/**
* Serializer used by connection factory to send and receive messages
*/
@Bean
public ByteArrayLengthHeaderSerializer byteArrayLengthHeaderSerializer() {
return new ByteArrayLengthHeaderSerializer(SERIALIZER_HEADER_SIZE);
}
@Bean
public AbstractClientConnectionFactory tcpClientConnectionFactory() {
TcpNetClientConnectionFactory connFactory =
new TcpNetClientConnectionFactory(props.getUrl(), props.getPort());
connFactory.setSerializer(byteArrayLengthHeaderSerializer());
connFactory.setDeserializer(byteArrayLengthHeaderSerializer());
connFactory.setSoTimeout(props.getSoTimeout());
if (props.isUseSSL()) {
connFactory.setTcpSocketFactorySupport(new DefaultTcpNetSSLSocketFactorySupport(() -> {
return SSLContext.getDefault();
}));
}
return connFactory;
}
/**
* Connection factory used to create TCP client socket connections
*/
@Bean
public AbstractClientConnectionFactory tcpCachedClientConnectionFactory() {
CachingClientConnectionFactory cachingConnFactory =
new CachingClientConnectionFactory(tcpClientConnectionFactory(), props.getMaxPoolSize());
cachingConnFactory.setConnectionWaitTimeout(props.getMaxPoolWait());
return cachingConnFactory;
}
使用此处发布的解决方案Configure keep alive to keep connection alive all the time 我可以保持连接打开,但我也想利用这些服务器保持活动消息并不时发送这些消息以检查连接是否仍然存在。这可以提高客户端的性能,因为如果套接字关闭,它不需要重新连接/创建新连接。
基于此,是否有人对如何使用 spring 集成来实现这一点提出建议?
【问题讨论】:
-
不清楚你的意思。您可以将
soKeepAlive设置为true,这样操作系统将通过发送ping 来保持套接字打开。然后,如果您不设置soTimeout,则套接字将无限期保持打开状态。 -
服务器会收到类似
KEEP_ALIVE_REQUEST的信息,并会发回KEEP_ALIVE_RESPONSE。我的问题是关于使用它来保持连接打开,但根据您的回复soKeepAlive和soTimeout一起可以解决问题。 -
更新:@GaryRussell 服务器将在 30 秒不活动后关闭套接字。基于此,spring 集成是否有任何功能可以用来发送那些特定的保持活动消息(以后台方式),以便可以重用客户端套接字?
标签: java spring sockets tcp spring-integration