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

如何在Camel 3.0.0中配置全局interceptSendToEndpoint拦截所有路由

解决Camel 3.0.0全局拦截HTTP组件流量的问题

在Camel 3.x版本中,默认的interceptSendToEndpoint只会作用于当前RouteBuilder内的路由,要让它全局生效覆盖上下文所有路由,有两种可靠的实现方式:

方法一:使用global()方法标记全局拦截器

直接在你的拦截器RouteBuilder中给interceptSendToEndpoint添加global()调用,这是Camel官方提供的全局拦截器标记方式,代码修改如下:

public class InterceptRoute extends RouteBuilder {

  @Override
  public void configure() throws Exception {
    interceptSendToEndpoint("http:*")
        .global() // 关键:标记为全局拦截器,作用于上下文所有路由
        .matchOnUriPrefix(true) // 可选:确保动态生成的HTTP端点(比如toD)也能被匹配到
        .process(exchange -> System.out.println("Hi from intercept"));
  }
}

注意点:

  • global()方法从Camel 2.20版本开始支持,3.0.0完全兼容,它会让拦截器应用到整个Camel上下文的所有路由,不管路由定义在哪个RouteBuilder中。
  • 如果需要同时拦截HTTPS流量,把匹配模式改成http*:*即可。
  • 添加matchOnUriPrefix(true)是为了适配toD这类动态生成的HTTP端点,确保前缀匹配生效。

方法二:通过CamelContext直接注册全局拦截器

如果第一种方式不生效,还可以在启动Camel上下文时,直接通过API注册全局拦截器,代码示例:

// 创建Camel上下文
CamelContext context = new DefaultCamelContext();

// 先添加所有业务路由
context.addRoutes(new Route1());
context.addRoutes(new Route2());

// 创建全局HTTP拦截器
SendToEndpointInterceptor httpInterceptor = new SendToEndpointInterceptor("http:*", true);
httpInterceptor.addAdvice(exchange -> System.out.println("Hi from intercept"));

// 将拦截器注册到上下文
context.getInterceptStrategy().addInterceptor(httpInterceptor);

// 启动上下文
context.start();

这种方式绕过了RouteBuilder的作用域限制,直接将拦截器绑定到整个上下文,适用于更复杂的配置场景。

内容的提问来源于stack exchange,提问作者Bara' Hashesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:24:42