Apache Camel如何根据Exchange属性动态设置重试次数?
解决Apache Camel条件化设置重试次数的问题
你的核心问题是onException不能嵌套在choice内部,Camel要求异常处理规则必须定义在路由顶层。以下两种方案可以实现根据Exchange属性动态控制重试次数:
方案一:动态表达式设置重试次数
利用Camel的maximumRedeliveries支持表达式的特性,直接根据positive属性计算重试次数:
from(RETRY_ONLINE_ENDPOINT) .routeId(RETRY_ONLINE_ROUTE_ID) // 顶层定义异常处理规则 .onException(HttpOperationFailedException.class) .log(LoggingLevel.INFO, "Caught: ${exchangeProperty.CamelExceptionCaught}, retried attempts: ${header.CamelRedeliveryCounter}") // 动态计算重试次数:positive为true时重试3次,否则0次(不重试) .maximumRedeliveries(simple("${exchangeProperty.positive} ? 3 : 0")) .handled(true) .bean(PostRetryBean.class) .end() // 执行业务逻辑 .bean(PostRetryBean.class);
这种方式通过Simple表达式直接返回对应重试次数,当positive为false时,重试次数设为0,自然不会触发重试。
方案二:给异常处理规则添加条件判断
通过onException的when方法,仅当positive为true时才启用重试逻辑:
from(RETRY_ONLINE_ENDPOINT) .routeId(RETRY_ONLINE_ROUTE_ID) // 仅当positive为true时,应用该异常重试规则 .onException(HttpOperationFailedException.class) .when(simple("${exchangeProperty.positive} == true")) .log(LoggingLevel.INFO, "Caught: ${exchangeProperty.CamelExceptionCaught}, retried attempts: ${header.CamelRedeliveryCounter}") .maximumRedeliveries(3) .handled(true) .bean(PostRetryBean.class) .end() // 执行业务逻辑 .bean(PostRetryBean.class);
这里的when条件会过滤Exchange,只有满足条件的请求才会触发该异常处理规则,不满足的请求遇到异常时不会重试。
错误原因说明
你之前的代码报错是因为Camel的onException必须定义在路由的顶层(或子路由顶层),不能嵌套在choice、loop这类处理器内部,否则会触发路由配置错误。
内容的提问来源于stack exchange,提问作者WesternGun
相关产品推荐
相关产品推荐

