如何使用Apache Camel路由将本地REST端点请求转发至其他服务端点
Apache Camel REST端点转发正确实现方案
你给出的写法核心问题是Camel路由端点必须指定组件前缀,不能直接写裸地址,转发HTTP请求需要依赖对应HTTP组件,且需要配置必要参数保证转发逻辑正确。
前置依赖
以Spring Boot集成场景为例,需要先引入对应组件依赖(Maven格式):
<!-- Camel Spring Boot核心依赖 --> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-spring-boot-starter</artifactId> <version>匹配你项目的Camel版本号</version> </dependency> <!-- HTTP转发组件 --> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-http-starter</artifactId> <version>匹配你项目的Camel版本号</version> </dependency> <!-- REST服务承载组件,若用Jetty可替换为camel-jetty-starter --> <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-servlet-starter</artifactId> <version>匹配你项目的Camel版本号</version> </dependency>
实现方式1:基础Route写法
from("servlet:get-something?matchOnUriPrefix=true") // 可选:移除原请求Host头避免转发时冲突 .removeHeaders("Host") // bridgeEndpoint=true 代表直接使用目标地址转发,不拼接原请求路径 .to("http:someIp:8081/get-something2?bridgeEndpoint=true&throwExceptionOnFailure=false");
如果使用Jetty作为服务容器,from节点写法调整为:
from("jetty:http://0.0.0.0:8080/get-something?matchOnUriPrefix=true")
实现方式2:REST DSL写法
先配置REST全局参数,再编写转发路由:
// 配置REST服务基础参数,指定承载组件和端口 restConfiguration() .component("servlet") .port(8080); rest() .path("/get-something") .get() .route() .removeHeaders("Host") .to("http:someIp:8081/get-something2?bridgeEndpoint=true&throwExceptionOnFailure=false");
核心参数说明
bridgeEndpoint=true:必须配置,否则Camel会将原请求的URI后缀拼接到目标地址后,导致目标路径错误throwExceptionOnFailure=false:可选配置,开启后目标服务返回4xx/5xx状态码时不会抛出异常,直接将原响应返回给调用方matchOnUriPrefix=true:可选配置,开启后可以匹配/get-something下的所有子路径请求
内容的提问来源于stack exchange,提问作者primElite
相关产品推荐
相关产品推荐

