首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Spring-Integration返回套接字超时时的错误消息

如何使用Spring-Integration返回套接字超时时的错误消息
EN

Stack Overflow用户
提问于 2014-06-02 07:47:15
回答 2查看 924关注 0票数 1

我正在使用Spring (Integration)提供套接字tcp连接。我对这个套接字有一个特定的超时。

当超时超过时,我不仅喜欢关闭连接(这已经起作用了),而且还返回自定义错误消息(或者不关闭连接,而是只返回错误消息)。这有可能吗?

代码语言:javascript
复制
@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;
}

更新:

代码语言:javascript
复制
@Bean
public ApplicationListener<TcpConnectionEvent> tcpErrorListener() {
    TcpConnectionEventListeningMessageProducer producer = new TcpConnectionEventListeningMessageProducer();
    producer.setEventTypes(new Class[] {TcpConnectionCloseEvent.class});
    producer.setOutputChannel(tcpErrorChannel()); //what to do here?
    return producer;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-02 09:39:08

实际上,任何封闭的连接都会发出TcpConnectionCloseEvent,您可以使用以下方法来处理它:

代码语言:javascript
复制
<int-event:inbound-channel-adapter channel="connectionClosedChannel" 
      event-types="org.springframework.integration.ip.tcp.connection.TcpConnectionCloseEvent"/>

有了它,您不仅可以关闭连接,而且可以使用该event-flow执行任何所需的逻辑。

更新

要从JavaConfig中使用它,请执行以下操作:

代码语言:javascript
复制
@Bean
public SmartApplicationListener tcpErrorListener() {
    ApplicationEventListeningMessageProducer producer = new ApplicationEventListeningMessageProducer();
    producer.setEventTypes(TcpConnectionCloseEvent.class);
    producer.setOutputChannel(tcpErrorChannel());
    return producer;
}

@Bean
public MessageChannel tcpErrorChannel() {
    return new DirectChannel();
}
票数 1
EN

Stack Overflow用户

发布于 2014-06-02 12:59:12

这个需求有点不寻常--当客户端收到自定义错误消息时,它会做什么?

目前没有一种简单的方法来拦截超时;您可以这样做,但是您必须对连接工厂和它创建的连接对象进行子类化,并重写handleReadException()方法。

直接在您自己的组件中处理套接字并使用消息传递网关向您的流发送消息可能要容易得多。或者,只需使组件成为MessagingGatewaySupport的子类。

或者,您可以在下游流中使用一些东西(并且不要设置超时)。当收到消息时,安排一个任务在10秒内发送错误消息。当下一条消息到达时,取消计划的任务并安排一个新的任务。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23989625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档