我正在使用Spring (Integration)提供套接字tcp连接。我对这个套接字有一个特定的超时。
当超时超过时,我不仅喜欢关闭连接(这已经起作用了),而且还返回自定义错误消息(或者不关闭连接,而是只返回错误消息)。这有可能吗?
@Bean
public TcpConnectionFactoryFactoryBean tcpFactory(Converter converter) {
TcpConnectionFactoryFactoryBean factory = new TcpConnectionFactoryFactoryBean();
factory.setType("server");
factory.setPort("8080");
factory.setSingleUse(true);
factory.setSoTimeout(10000); //10s; how to return error message?
return factory;
}更新:
@Bean
public ApplicationListener<TcpConnectionEvent> tcpErrorListener() {
TcpConnectionEventListeningMessageProducer producer = new TcpConnectionEventListeningMessageProducer();
producer.setEventTypes(new Class[] {TcpConnectionCloseEvent.class});
producer.setOutputChannel(tcpErrorChannel()); //what to do here?
return producer;
}发布于 2014-06-02 09:39:08
实际上,任何封闭的连接都会发出TcpConnectionCloseEvent,您可以使用以下方法来处理它:
<int-event:inbound-channel-adapter channel="connectionClosedChannel"
event-types="org.springframework.integration.ip.tcp.connection.TcpConnectionCloseEvent"/>有了它,您不仅可以关闭连接,而且可以使用该event-flow执行任何所需的逻辑。
更新
要从JavaConfig中使用它,请执行以下操作:
@Bean
public SmartApplicationListener tcpErrorListener() {
ApplicationEventListeningMessageProducer producer = new ApplicationEventListeningMessageProducer();
producer.setEventTypes(TcpConnectionCloseEvent.class);
producer.setOutputChannel(tcpErrorChannel());
return producer;
}
@Bean
public MessageChannel tcpErrorChannel() {
return new DirectChannel();
}发布于 2014-06-02 12:59:12
这个需求有点不寻常--当客户端收到自定义错误消息时,它会做什么?
目前没有一种简单的方法来拦截超时;您可以这样做,但是您必须对连接工厂和它创建的连接对象进行子类化,并重写handleReadException()方法。
直接在您自己的组件中处理套接字并使用消息传递网关向您的流发送消息可能要容易得多。或者,只需使组件成为MessagingGatewaySupport的子类。
或者,您可以在下游流中使用一些东西(并且不要设置超时)。当收到消息时,安排一个任务在10秒内发送错误消息。当下一条消息到达时,取消计划的任务并安排一个新的任务。
https://stackoverflow.com/questions/23989625
复制相似问题