You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 09:55:23