2017-06-13 117 views
2

如何处理Java DSL流中的错误处理?Spring集成Java DSL:处理错误/异常的策略?

假设我有一个写入Rabbit(或数据库)的简单流程。

@Bean 
public IntegrationFlow setupRabbitFlow() { 
    return IntegrationFlows.from(publishSubscribeChannel) 
      .handle((p, h) -> rabbitPublishActivator.publishToRabbit(p)) 
      .get(); 
} 

这样的操作可能会导致由于数据库问题或中间连接失败而导致的错误。

如果在“publishToRabbit”步骤中发生某些异常,我该如何增强对所采取操作的流程声明?

+0

为什么不简单地在'publishToRabbit'方法中记录异常? – Jobin

+0

简单的日志记录是不够的,我可能想调用一些逻辑来重新尝试稍后发送。 –

回答

1

如果你谈论重试和类似的,你应该看看RequestHandlerRetryAdvice

另一方面,.handle()有第二个参数 - 端点配置器。您可以指定.advice()

.handle((GenericHandler<?>) (p, h) -> { 
        throw new RuntimeException("intentional"); 
       }, e -> e.advice(retryAdvice())) 

    @Bean 
    public RequestHandlerRetryAdvice retryAdvice() { 
     RequestHandlerRetryAdvice requestHandlerRetryAdvice = new RequestHandlerRetryAdvice(); 
     requestHandlerRetryAdvice.setRecoveryCallback(new ErrorMessageSendingRecoverer(recoveryChannel())); 
     return requestHandlerRetryAdvice; 
    } 
+0

另外,如果你的'publishToRabbit'使用'RabbitTemplate',你可以用'RetryTemplate'配置它。 –

+0

谢谢,如果我只是需要处理一个错误,我该如何配置? –

+0

关于此问题,有'ExpressionEvaluatingRequestHandlerAdvice':http://docs.spring.io/spring-integration/docs/4.3.10.RELEASE/reference/html/messaging-endpoints-chapter.html#expression-advice –