异常子句重新投递
异常子句 - 重新投递
配置 RedeliveryPolicy(redeliver 选项)
RedeliveryPolicy 要求使用死信通道作为错误处理器。死信通道支持在将消息交换发送到死信端点之前,尝试多次重新投递该消息交换。关于重新投递以及可用的重新投递选项的更多信息,请参见死信通道。
onException 默认不进行重新投递
默认情况下,任何异常子句都不会重新投递!(因为它将 maximumRedeliveries 选项设置为 0)。
有时你希望按异常类型分别配置重新投递策略。在上面的示例中,默认情况下,如果发生 org.apache.camel.ValidationException,消息将不会被重新投递;然而如果发生其他异常,例如 IOException 或其他异常,路由将根据死信通道的设置进行重试。
不过,如果你希望自定义 RedeliveryPolicy 对象上的任意方法,可以通过流式 API 来实现。下面让 org.apache.camel.ValidationException 发生时最多重试两次。
- Java
- XML
- YAML
onException(ValidationException.class)
.maximumRedeliveries(2);<onException>
<exception>com.mycompany.ValidationException</exception>
<redeliveryPolicy maximumRedeliveries="2"/>
</onException>- onException:
exception:
- org.apache.camel.ValidationException
redeliveryPolicy:
maximumRedeliveries: 2您可以自定义 RedeliveryPolicy 的任意选项,例如将延迟时间设置为 5000 毫秒:
- Java
- XML
- YAML
onException(ValidationException.class)
.maximumRedeliveries(2).redeliveryDelay(5000);<onException>
<exception>com.mycompany.ValidationException</exception>
<redeliveryPolicy maximumRedeliveries="2" redeliveryDelay="5000"/>
</onException>- onException:
exception:
- org.apache.camel.ValidationException
redeliveryPolicy:
maximumRedeliveries: 2
redeliveryDelay: 5000重试投递的入口点
所有重试投递都从失败的位置开始。因此对于如下路由:
仅限 Java:重试从失败位置开始
onException(ConnectException.class)
.from("direct:start")
.process("processor1")
.process("processor2") // <--- throws a ConnectException
.to("mock:theEnd")将从 processor2 开始重试——而不是整个路由。
异步延迟重投递
Camel 提供了一种功能,在等待延迟重投递发生时不阻塞。不过,如果你使用事务路由,那么 Camel 将会阻塞,因为事务管理器要求在同一线程上下文中执行所有工作。你可以通过 asyncDelayedRedelivery 选项启用非阻塞的异步行为。该选项可以在 errorHandler、onException 或重投递策略上进行设置。
默认情况下,错误处理器会创建并使用一个调度线程池,以便在未来触发重投递。你也可以在错误处理器上配置 executorServiceRef,以指定注册表中某个共享线程池的引用,或者指定一个线程池 profile,从而可以控制线程池的相关设置。
捕获多个异常
可以捕获多个异常,示例如下:
- Java
- XML
- YAML
在 Java DSL 中,你可以添加多个异常,并用逗号分隔。
onException(MyBusinessException.class, MyOtherBusinessException.class)
.maximumRedeliveries(2)
.to("activemq:businessFailed");而在 XML DSL 中,只需再添加一个 exception 元素:
<onException>
<exception>com.mycompany.MyBusinessException</exception>
<exception>com.mycompany.MyOtherBusinessException</exception>
<redeliveryPolicy maximumRedeliveries="2"/>
<to uri="activemq:businessFailed"/>
</onException>而在 YAML DSL 中,你只需在数组中再添加一个异常即可:
- onException:
exception:
- com.mycompany.MyBusinessException
- com.mycompany.MyOtherBusinessException
redeliveryPolicy:
maximumRedeliveries: 2
steps:
- to:
uri: activemq:businessFailed评论
登录后参与评论
KnowForge