Spring Integration Обработка исключений SFTP

Я конвертирую каждое входящее сообщение в файл и загружаю на SFTP-сервер. Я получаю огромные журналы трассировки стека исключений, когда SFTP недоступен во время загрузки файла. Это происходит при каждом входящем сообщении. Просто интересно, есть ли какое-нибудь более чистое решение, где я могу перехватывать эти исключения и регистрировать настраиваемое сообщение с помощью моего КОНФИГУРИРОВАННОГО РЕГИСТРАТОРА?

   <bean id="sftpSessionFactory" class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
        <property name="host" value="${ftp.host}"></property>
        <property name="port" value="22" />
        <property name="user" value="${ftp.username}"></property>
        <property name="password" value="${ftp.password}"></property>
        <property name="timeout" value="2000"></property>
    </bean>

    <int:publish-subscribe-channel id="sftpChannel"></int:publish-subscribe-channel>
    <sftp:outbound-channel-adapter id="sftpOutboundAdapter" auto-create-directory="true" session-factory="sftpSessionFactory" channel="sftpChannel" charset="UTF-8" remote-directory="${ftp.path}" remote-filename-generator-expression="headers[fileName] + '.xml'">
        <sftp:request-handler-advice-chain>
            <bean class="org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice">
                <property name="onSuccessExpression" value="payload.delete()" />
            </bean>
        </sftp:request-handler-advice-chain>
    </sftp:outbound-channel-adapter>

Я изменил конфигурацию, как показано ниже:

<int:publish-subscribe-channel id="sftpChannel"></int:publish-subscribe-channel>
<sftp:outbound-channel-adapter id="sftpOutboundAdapter" auto-create-directory="true" session-factory="sftpSessionFactory" channel="sftpChannel" charset="UTF-8" remote-directory="${spectrum.ftp.path}" remote-filename-generator-expression="headers[fileName] + '.xml'">
    <sftp:request-handler-advice-chain>
        <bean class="org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice">
            <property name="onSuccessExpression" value="payload.delete()" />
            <property name="failureChannel" ref="errorChannel" />
        </bean>
    </sftp:request-handler-advice-chain>
</sftp:outbound-channel-adapter>

Я отправляю этот файл, используя:

    outputChannel = context.getBean("sftpChannel", org.springframework.integration.MessageChannel.class);
line#120->     if (outputChannel.send(payload)) {
                        ptsoLog.info("Successfully uploaded file : " + fileName + ".xml");
                    }else{
                        ptsoLog.error("File upload failed : " + e.getMessage());
                    }

но все равно получите это исключение:

    org.springframework.integration.MessagingException: Failed to execute on session
        at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:306) ~[spring-integration-file-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:190) ~[spring-integration-file-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:182) ~[spring-integration-file-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.file.remote.handler.FileTransferringMessageHandler.handleMessageInternal(FileTransferringMessageHandler.java:112) ~[spring-integration-file-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:73) ~[spring-integration-core-3.0.5.RELEASE.jar:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_30]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_30]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_30]
        at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_30]
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) ~[spring-aop-3.2.4.RELEASE.jar:3.2.4.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) ~[spring-aop-3.2.4.RELEASE.jar:3.2.4.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) ~[spring-aop-3.2.4.RELEASE.jar:3.2.4.RELEASE]
        at org.springframework.integration.handler.advice.AbstractRequestHandlerAdvice$1.execute(AbstractRequestHandlerAdvice.java:72) ~[spring-integration-core-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice.doInvoke(ExpressionEvaluatingRequestHandlerAdvice.java:115) ~[spring-integration-core-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.handler.advice.AbstractRequestHandlerAdvice.invoke(AbstractRequestHandlerAdvice.java:68) ~[spring-integration-core-3.0.5.RELEASE.jar:na]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) ~[spring-aop-3.2.4.RELEASE.jar:3.2.4.RELEASE]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) ~[spring-aop-3.2.4.RELEASE.jar:3.2.4.RELEASE]
        at $Proxy27.handleMessage(Unknown Source) ~[na:na]
        at org.springframework.integration.dispatcher.BroadcastingDispatcher.invokeHandler(BroadcastingDispatcher.java:141) ~[spring-integration-core-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.dispatcher.BroadcastingDispatcher.dispatch(BroadcastingDispatcher.java:123) ~[spring-integration-core-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77) ~[spring-integration-core-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:178) ~[spring-integration-core-3.0.5.RELEASE.jar:na]
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:149) ~[spring-integration-core-3.0.5.RELEASE.jar:na]
        at com.xx.xx.xxx.outputMessage(xxxOutputter.java:120) ~[src/:na]



        Caused by: java.lang.IllegalStateException: failed to create SFTP Session
            at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:321) ~[spring-integration-sftp-3.0.5.RELEASE.jar:na]
            at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:295) ~[spring-integration-file-3.0.5.RELEASE.jar:na]
            ... 48 common frames omitted
        Caused by: java.lang.IllegalStateException: failed to connect
            at org.springframework.integration.sftp.session.SftpSession.connect(SftpSession.java:250) ~[spring-integration-sftp-3.0.5.RELEASE.jar:na]
            at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:316) ~[spring-integration-sftp-3.0.5.RELEASE.jar:na]
            ... 49 common frames omitted
        Caused by: com.jcraft.jsch.JSchException: timeout: socket is not established
            at com.jcraft.jsch.Util.createSocket(Util.java:394) ~[jsch-0.1.51.jar:na]
            at com.jcraft.jsch.Session.connect(Session.java:215) ~[jsch-0.1.51.jar:na]
            at com.jcraft.jsch.Session.connect(Session.java:183) ~[jsch-0.1.51.jar:na]
            at org.springframework.integration.sftp.session.SftpSession.connect(SftpSession.java:241) ~[spring-integration-sftp-3.0.5.RELEASE.jar:na]
            ... 50 common frames omitted

Caused by: java.lang.IllegalStateException: failed to create SFTP Session
    at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:321) ~[spring-integration-sftp-3.0.5.RELEASE.jar:na]
    at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:295) ~[spring-integration-file-3.0.5.RELEASE.jar:na]
    ... 47 common frames omitted
Caused by: java.lang.IllegalStateException: failed to connect
    at org.springframework.integration.sftp.session.SftpSession.connect(SftpSession.java:250) ~[spring-integration-sftp-3.0.5.RELEASE.jar:na]
    at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:316) ~[spring-integration-sftp-3.0.5.RELEASE.jar:na]
    ... 48 common frames omitted
Caused by: com.jcraft.jsch.JSchException: timeout: socket is not established
    at com.jcraft.jsch.Util.createSocket(Util.java:394) ~[jsch-0.1.51.jar:na]
    at com.jcraft.jsch.Session.connect(Session.java:215) ~[jsch-0.1.51.jar:na]
    at com.jcraft.jsch.Session.connect(Session.java:183) ~[jsch-0.1.51.jar:na]
    at org.springframework.integration.sftp.session.SftpSession.connect(SftpSession.java:241) ~[spring-integration-sftp-3.0.5.RELEASE.jar:na]
    ... 49 common frames omitted

person shiv    schedule 13.11.2014    source источник


Ответы (1)


Поскольку вы уже используете ExpressionEvaluatingRequestHandlerAdvice, вы можете указать вторую опцию onFailureExpression вместе с failureChannel, чтобы отправить ErrorMessage с Exception в другой канал и выполнить некоторые преобразования и регистрацию в этом потоке.

ОБНОВЛЕНИЕ

Спасибо за столь обширную информацию по проблеме.

Итак, как мы видим по StackTrace, ExpressionEvaluatingRequestHandlerAdvice тоже присутствует.

И что я могу сказать по его исходному коду, он отправляет ErrorMessage в failureChannel, только если вы укажете onFailureExpression. (#root) вам должно хватить.

И есть еще один вариант - trapException = true, если вы хотите подавить это исключение для повторной передачи вызывающему.

person Artem Bilan    schedule 13.11.2014
comment
Спасибо за ответ. Он по-прежнему не работает со следующей конфигурацией. <int:service-activator input-channel="errorChannel" ref="errorLogger" method="logError" /> <bean id="errorLogger" class="com.smarttrade.posttrade.ErrorLogger" /> - person shiv; 13.11.2014
comment
Я всегда получаю это исключение в моем журнале. Я хотел бы подавить это исключение, поскольку это исключение IllegalStateException наносит ущерб всему рабочему процессу моей системы. 'Причина: java.lang.IllegalStateException: не удалось подключиться к org.springframework.integration.sftp.session.SftpSession.connect (SftpSession.java:250) ~ [spring-integration-sftp-3.0.5.RELEASE.jar: na] в org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession (DefaultSftpSessionFactory.java:316) ~ [spring- Вызвано: com.jcraft.jsch.JSchException: тайм-аут: сокет не установлен - person shiv; 13.11.2014
comment
Здорово! Поделитесь, пожалуйста, еще StackTrace на свой вопрос, и мы увидим, как вам помочь. С другой стороны: вы имеете в виду, что исключение не передается failureChannel? - person Artem Bilan; 13.11.2014
comment
Верно. Я добавил к своему вопросу измененную конфигурацию и трассировку стека. Пожалуйста, посмотрите. - person shiv; 13.11.2014
comment
Ага .. Недостаточно StackTrace. Мне нужно понять суть FileTransferringMessageHandler, чтобы понять, почему ExpressionEvaluatingRequestHandlerAdvice не улавливает JSchException - person Artem Bilan; 13.11.2014
comment
Я добавил вызывающий код и полную трассировку стека. пожалуйста, проверьте. - person shiv; 13.11.2014
comment
Спасибо, Артем. Пробую ваши предложения. - person shiv; 13.11.2014
comment
Большое спасибо. Он хорошо работал с <property name="trapException" value="true" /> - person shiv; 13.11.2014