Spring-Integration:异常时未发送Tcp服务器响应

时间:2019-03-10 22:41:42

标签: spring-boot tcp spring-integration

我将传统的tcp服务器代码迁移到spring-boot中,并添加了spring-intergration(基于注释)依赖性来处理tcp套接字连接。

我的入站通道是tcpIn(),出站通道是serviceChannel(),并且我创建了一个自定义Channel [exceptionEventChannel()]来保存异常事件消息。

我有一个自定义的序列化器/反序列化方法(ByteArrayLengthPrefixSerializer()扩展了AbstractPooledBufferByteArraySerializer),还有一个MessageHandler @ServiceActivator方法,用于将响应发送回tcp客户端。


//SpringBoot 2.0.3.RELEASE, Spring Integration 5.0.6.RELEASE

package com.test.config;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.event.inbound.ApplicationEventListeningMessageProducer;
import org.springframework.integration.ip.IpHeaders;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.TcpSendingMessageHandler;
import org.springframework.integration.ip.tcp.connection.*;
import org.springframework.integration.ip.tcp.serializer.TcpDeserializationExceptionEvent;
import org.springframework.integration.router.ErrorMessageExceptionTypeRouter;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.messaging.MessagingException;

import java.io.IOException;

@Configuration
@IntegrationComponentScan
public class TcpConfiguration {
    @SuppressWarnings("unused")
    @Value("${tcp.connection.port}")
    private int tcpPort;

    @Bean
    TcpConnectionEventListener customerTcpListener() {
        return new TcpConnectionEventListener();
    }

    @Bean
    public MessageChannel tcpIn() {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel serviceChannel() {
        return new DirectChannel();
    }

    @ConditionalOnMissingBean(name = "errorChannel")
    @Bean
    public MessageChannel errorChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageChannel exceptionEventChannel() {
        return new DirectChannel();
    }

    @Bean
    public ByteArrayLengthPrefixSerializer byteArrayLengthPrefixSerializer() {
        ByteArrayLengthPrefixSerializer byteArrayLengthPrefixSerializer = new ByteArrayLengthPrefixSerializer();
        byteArrayLengthPrefixSerializer.setMaxMessageSize(98304); //max allowed size set to 96kb
        return byteArrayLengthPrefixSerializer;
    }

    @Bean
    public AbstractServerConnectionFactory tcpNetServerConnectionFactory() {
        TcpNetServerConnectionFactory tcpServerCf = new TcpNetServerConnectionFactory(tcpPort);
        tcpServerCf.setSerializer(byteArrayLengthPrefixSerializer());
        tcpServerCf.setDeserializer(byteArrayLengthPrefixSerializer());
        return tcpServerCf;

    }

    @Bean
    public TcpReceivingChannelAdapter tcpReceivingChannelAdapter() {
        TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
        adapter.setConnectionFactory(tcpNetServerConnectionFactory());
        adapter.setOutputChannel(tcpIn());
        adapter.setErrorChannel(exceptionEventChannel());
        return adapter;
    }

    @ServiceActivator(inputChannel = "exceptionEventChannel", outputChannel = "serviceChannel")
    public String handle(Message<MessagingException> msg) {
        //String unfilteredMessage = new String(byteMessage, StandardCharsets.US_ASCII);
        System.out.println("-----------------EXCEPTION ==> " + msg);
        return msg.toString();
    }

    @Transformer(inputChannel = "errorChannel", outputChannel = "serviceChannel")
    public String transformer(String msg) {
        //String unfilteredMessage = new String(byteMessage, StandardCharsets.US_ASCII);
        System.out.println("-----------------ERROR ==> " + msg);
        return msg.toString();
    }


    @ServiceActivator(inputChannel = "serviceChannel")
    @Bean
    public TcpSendingMessageHandler out(AbstractServerConnectionFactory cf) {
        TcpSendingMessageHandler tcpSendingMessageHandler = new TcpSendingMessageHandler();
        tcpSendingMessageHandler.setConnectionFactory(cf);
        return tcpSendingMessageHandler;
    }


    @Bean
    public ApplicationListener<TcpDeserializationExceptionEvent> listener() {
        return new ApplicationListener<TcpDeserializationExceptionEvent>() {

            @Override
            public void onApplicationEvent(TcpDeserializationExceptionEvent tcpDeserializationExceptionEvent) {
                exceptionEventChannel().send(MessageBuilder.withPayload(tcpDeserializationExceptionEvent.getCause())
                        .build());
            }

        };
    }
}

tcpIn()中的消息被发送到一个单独的@Component类中的@ServiceActivator方法,该类的结构如下:

@Component
public class TcpServiceActivator {

    @Autowired
    public TcpServiceActivator() {
    }


    @ServiceActivator(inputChannel = "tcpIn", outputChannel = "serviceChannel")
    public String service(byte[] byteMessage) {
     // Business Logic returns String Ack Response
    }

在运行成功方案时,我没有任何问题。我的Tcp TestClient得到了预期的Ack响应。

但是,当我尝试模拟异常时,说Deserializer Exception,该异常消息不会作为对Tcp Client的响应发送回去。 我可以看到我的应用程序监听器正在获取TcpDeserializationExceptionEvent并将消息发送到exceptionEventChannel。 @ServiceActivator方法handle(Message msg)也输出我的异常消息。但是它永远不会到达MessageHandler方法out(AbstractServerConnectionFactory cf)内部的断点(在调试模式下)。

我正在努力了解出什么问题了。感谢您的任何提前帮助。


UPDATE:我注意到套接字由于异常而被关闭,然后才可以发送响应。我正在尝试解决此问题的方法

解决方案更新(2019年3月12日):

由Gary提供,我编辑了反序列化器,以返回可以通过@Router方法跟踪并重定向到errorChannel的消息。然后,侦听errorchannel的ServiceActivator将所需的错误消息发送到outputChannel。此解决方案似乎有效。

我在ByteArrayLengthPrefixSerializer中使用的反序列化方法返回了Gary建议的“特殊值”,而不是原始的InputStream消息。

    public byte[] doDeserialize(InputStream inputStream, byte[] buffer) throws IOException {
        boolean isValidMessage = false;
        try {
            int messageLength = this.readPrefix(inputStream);
            if (messageLength > 0 && fillUntilMaxDeterminedSize(inputStream, buffer, messageLength)) {
                return this.copyToSizedArray(buffer, messageLength);
            }
            return EventType.MSG_INVALID.getName().getBytes(); 
        } catch (SoftEndOfStreamException eose) {
            return EventType.MSG_INVALID.getName().getBytes();
        }
    }

我还创建了一些新的通道来容纳我的路由器,因此流程如下:

成功流程 tcpIn(@Router)-> serviceChannel(@具有业务逻辑的serviceActivator)-> outputChannel(将响应发送给客户端的@serviceActivator)

异常流程 tcpIn(@Router)-> errorChannel(准备错误响应消息的@serviceActivator)-> outputChannel(将响应发送给客户端的@serviceActivator)

我的@Router和'errorHandling'@serviceActivator-

    @Router(inputChannel = "tcpIn", defaultOutputChannel = "errorChannel")
    public String messageRouter(byte[] byteMessage) {
        String unfilteredMessage = new String(byteMessage, StandardCharsets.US_ASCII);
        System.out.println("------------------> "+unfilteredMessage);
        if (Arrays.equals(EventType.MSG_INVALID.getName().getBytes(), byteMessage)) {
            return "errorChannel";
        }
        return "serviceChannel";
    }


    @ServiceActivator(inputChannel = "errorChannel", outputChannel = "outputChannel")
    public String errorHandler(byte[] byteMessage) {
        return Message.ACK_RETRY;
    }

1 个答案:

答案 0 :(得分:0)

错误通道用于处理在处理消息时发生的异常。在创建消息之前,反序列化错误发生(反序列化程序对消息的有效载荷进行解码)。

反序列化异常是致命的,如您所见,套接字已关闭。

一种选择是在反序列化器中捕获异常,并返回一个“特殊”值,表示发生反序列化异常,然后在主流中检查该值。