如果您是 Camel 新手,并且真的想深入了解它,我会推荐克劳斯·易卜生 (Claus Ibsen) 的一本书 Camel in Action。正在制作第二版,19 章中有 14 章已经完成,所以你也可以试一试。
如果这有点太多,在线文档还不错,您可以从中找到基础知识。对于错误处理,我建议从一般错误处理页面开始,然后转到错误处理程序文档和异常策略文档。
一般来说,死信通道是要走的路——骆驼会在重试次数用尽后自动发送到DLC,你只需要自己定义DLC。顾名思义,它是一个通道,实际上并不需要是一个队列——您可以写入文件、调用 Web 服务、将消息提交到消息队列或只写入日志,这完全取决于您。
// error-handler DLC, will send to HTTP endpoint when retries are exhausted
errorHandler(deadLetterChannel("http4://my.webservice.hos/path")
.useOriginalMessage()
.maximumRedeliveries(3)
.redeliveryDelay(5000))
// exception-clause DLC, will send to HTTP endpoint when retries are exhausted
onException(NetworkException.class)
.handled(true)
.maximumRedeliveries(5)
.backOffMultiplier(3)
.redeliveryDelay(15000)
.to("http4://my.webservice.hos/otherpath");
我自己一直更喜欢拥有一个消息队列,然后从那里消费以进行任何其他恢复或报告。我通常包括失败细节,比如交换 ID 和路由 ID、消息头、错误消息,有时甚至是堆栈跟踪。正如您可以想象的那样,生成的消息增长了很多,但它极大地简化了故障排除和调试,尤其是在您拥有大量组件和服务的环境中。这是来自我的一个项目的示例 DLC 消息:
public class DeadLetterChannelMessage {
private String timestamp = Times.nowInUtc().toString();
private String exchangeId;
private String originalMessageBody;
private Map<String, Object> headers;
private String fromRouteId;
private String errorMessage;
private String stackTrace;
@RequiredByThirdPartyFramework("jackson")
private DeadLetterChannelMessage() {
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public DeadLetterChannelMessage(Exchange e) {
exchangeId = e.getExchangeId();
originalMessageBody = e.getIn().getBody(String.class);
headers = Collections.unmodifiableMap(e.getIn().getHeaders());
fromRouteId = e.getFromRouteId();
Optional.ofNullable(e.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class))
.ifPresent(throwable -> {
errorMessage = throwable.getMessage();
stackTrace = ExceptionUtils.getStackTrace(throwable);
});
}
// getters
}
从死信队列中消费时,路由 ID 可以告诉您故障源自何处,因此您可以实现特定于处理来自那里的错误的路由:
// general DLC handling route
from("{{your.dlc.uri}}")
.routeId(ID_REPROCESSABLE_DLC_ROUTE)
.removeHeaders(Headers.ALL)
.unmarshal().json(JsonLibrary.Jackson, DeadLetterChannelMessage.class)
.toD("direct:reprocess_${body.fromRouteId}"); // error handling route
// handle errors from `myRouteId`
from("direct:reprocess_myRouteId")
.log("Error: ${body.errorMessage} for ${body.originalMessageBody}");
// you'll probably do something better here, e.g.
// .convertBodyTo(WebServiceErrorReport.class) // requires a converter
// .process(e -> { //do some pre-processing, like setting headers/properties })
// .toD("http4://web-service-uri/path"); // send to web-service
// for routes that have no DLC handling supplied
onException(DirectConsumerNotAvailableException.class)
.handled(true)
.useOriginalMessage()
.removeHeaders(Headers.ALL)
.to({{my.unreprocessable.dlc}}); // errors that cannot be recovered from