我有一个需要将文件异步上传到Sftp服务器的过程。因此,在探索了有关网关的异步的更多信息之后,我发现我需要在@MessagingGateway
参数中定义错误通道,然后在处理程序中处理传播到错误通道的异常,但是我觉得这种方式对我来说很复杂,因为我必须更新Pojo字段并根据文件上传,成功或失败,将其持久保存到数据库中。
因此,我想到了一个带有注释的自定义方法@Async
并调用网关方法。还使用try块环绕网关方法并捕获下游发生的任何异常
代码样例:
@Async
void upload(Resource file, FileStatus fileStatus){
try{
uploadGateway.upload(file,fileStatus.getFilePath(),fileStatus.getFileName());
}catch(RuntimeException e){
fileStatus.setUploadStatus("Failed");
//save into db
}
}
上载没有错误通道的网关,以便可以将错误发送回呼叫者
@MessagingGateway
public interface UploadGateway {
@Gateway(requestChannel = "input.channel")
void upload(@Payload Resource file, @Header("path") String path, @Header("name") String fileName);
}
处理程序:
@Bean
public IntegrationFlow uploadDocument() {
return IntegrationFlows.from("input.channel")
.log(LoggingHandler.Level.WARN)
.handle(Sftp.outboundAdapter(sftpSessionFactory(), FileExistsMode.FAIL)
.autoCreateDirectory(true)
.remoteDirectoryExpression("headers['path']")
.fileNameExpression("headers['name']"))
.get();
}
问题:如果我以这种方式处理错误,后果将是什么?这是处理下游流量中发生的任何错误的正确方法吗?
由于@MessagingGateway
像消息传递中的RPC一样,完全可以在这样的方法调用上捕获异常。由于您使流程完全同步,因此它就像典型的Java异常子系统一样工作。
您对异步错误处理的关注errorChannel
确实很有意义,因为它的复杂度与标准Java异步方法处理及其错误处理相似。
另一方面,errorChannel
如果在其他流程中使用一些复杂的逻辑,确实值得推荐通过下游处理错误。另外,您将返回一些补偿消息。
然而,归根结底,选择权由您自己决定:自己处理错误没有缺点。
有关更多思考的内容,请参见错误处理章节。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句