使用camel,我想发送一个HTTP请求,如果失败,则采取一些纠正措施并再次尝试。
发送请求被包装在direct
路由中,并且需要生成唯一的 token ,此外请求应该完全相同。如果请求第二次失败,它应该以“正常”方式失败。
我希望发送逻辑在它自己的路由中,因为有时我想调用它而不重试。
如何使用 Camel DSL 设置此场景?我尝试了 onException 和 errorHandler 的各种组合,但它似乎甚至没有捕获异常。
示例(不起作用):
from("direct:send-request-no-retry")
.setHeader("token").exchange(this::generateToken)
.to("http://example.com");
from("direct:fix-the-error")
// ...
;
from("direct:send-request")
.onException(HttpOperationFailedException.class)
.to("direct:fix-the-error")
.maximumRedeliveries(1)
.useOriginalMessage()
.end()
.to("direct:send-request-no-retry");
最佳答案
我主要使用 onException() 子句作为全局异常处理程序。通过快速测试,当直接放入路由中时,它确实不会捕获异常。我想到的几个选项是:
第一个选项 do-try 子句:
from("direct:send-request")
.doTry()
.to("direct:send-request-no-retry")
.doCatch(HttpOperationFailedException.class)
.to("direct:fix-the-error")
.to("direct:send-request-no-retry")
.doFinally()
.whatevs()
.endDoTry();
但这有点笨拙,因为您必须再次从 doCatch 子句处理异常。另一种是从“发送请求不重试”中抛出自定义异常。
from("direct:send-request-no-retry")
.setHeader("token").exchange(this::generateToken)
.doTry()
.to("http://example.com")
.doCatch(HttpOperationFailedException.class)
.throwException(new CustomExceptionThatExtendsRunTimeException())
.doFinally();
onException(CustomExceptionThatExtendsRunTimeException.class)
.handled(true)
.to("direct:fix-the-error")
.maximumRedeliveries(1)
.useOriginalMessage()
.to("direct:send-request-no-retry")
.end();
我没有对此进行测试,所以我不确定这是否会创建无限反馈循环,或者最大重新交付是否会切断它。如果确实如此,您可以实现另一个“direct:send-request-no-retry”路由,该路由不会抛出 customException,而只是默默失败,或者抛出 HttpOperationFailedException 并从 onException() 传递请求。或者将 retryAmount 设置为 header 并在 onException 处理程序中检查该 header 以查看我们是否要重试。
customException 的目的是让 onException() 子句捕获指定类型的每个路由中的所有异常。而且我认为您不想将每个失败的 http 请求传递到您的重试路由。
关于java - 如何重试 Camel 直达路线一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59272567/