一、背景
在 LightESB 中,HttpRequestSrv 使用 Camel Undertow 组件同时承担两类职责:
- 对外监听 HTTP 请求(Listener)
- 作为客户端转发请求到下游 HTTP 接口(Request)
该模式适用于"接入层快速编排":统一接收入口请求、记录链路日志、转发到后端服务并返回响应。
二、服务配置总览
HttpRequestSrv/v1.0.0/common.config.properties 中的关键配置:
server.port=18083:服务监听端口HTTP.Listener=true:启用 HTTP 监听system.components=undertowhttp:启用 undertow 相关组件能力
HttpRequestSrv/v1.0.0/service.config.properties 中定义了服务元信息:
service.name=HttpRequestSrvservice.version=1.0.0
三、HTTP Listener:接收外部请求
在 http-request-route.xml 中,入口路由如下:
xml
<from uri="undertow:http://0.0.0.0:{{server.port}}/api/httprequest/test?httpMethodRestrict=POST" />
说明:
undertow:http://0.0.0.0:{{server.port}}/...:监听所有网卡地址,端口来自配置server.porthttpMethodRestrict=POST:仅允许 POST,非 POST 会被拒绝- 对外实际入口为:
http://localhost:18083/api/httprequest/test
路由中通过 servicelog 打印入口与完成日志,便于定位请求链路。
四、HTTP Request:转发到下游接口
同一条路由内,使用 HTTP 生产者向下游转发:
xml
<to uri="http://0.0.0.0:18083/api/test?httpMethod=POST&contentType=application/json&bridgeEndpoint=true&connectTimeout=5000&socketTimeout=30000"/>
关键参数:
httpMethod=POST:转发请求方法contentType=application/json:声明内容类型bridgeEndpoint=true:桥接模式,避免 Camel 修改目标端点行为connectTimeout=5000:连接超时 5 秒socketTimeout=30000:读超时 30 秒
该下游地址由本服务内另一条测试路由承接:
xml
<from uri="undertow:http://0.0.0.0:{{server.port}}/api/test?httpMethodRestrict=POST"/>
<setBody>
<simple>{"message": "HTTP Response Test"}</simple>
</setBody>
因此,入口请求会被转发到本服务的 /api/test,最终得到 JSON 响应。
五、端到端请求示例
1) 调用入口 Listener
bash
curl -X POST "http://localhost:18083/api/httprequest/test" ^
-H "Content-Type: application/json" ^
-d "{\"orderId\":\"A1001\",\"amount\":99.8}"
预期:
- 请求被
http-request-route接收 - 路由转发到
/api/test - 返回:
{"message": "HTTP Response Test"}
2) 直接调用测试下游接口
bash
curl -X POST "http://localhost:18083/api/test" ^
-H "Content-Type: application/json" ^
-d "{}"
预期直接返回固定响应,用于验证下游可用性。
六、常见问题与排查
-
404 或连接失败
- 检查服务是否启动
- 检查
server.port是否为18083 - 检查路由文件是否已被加载
-
405 Method Not Allowed
- 路由限制了
POST,确认请求方法是否正确
- 路由限制了
-
转发超时
- 检查
connectTimeout、socketTimeout参数 - 检查下游
/api/test是否可达
- 检查
-
日志中看不到请求体
- 已配置
servicelog的showBody=true - 若请求体过长,调整
maxBodyLength
- 已配置
七、总结
HttpRequestSrv 展示了 Camel Undertow 的典型双向能力:
同一服务中既能做 HTTP Listener(接入),也能做 HTTP Request(转发)。
这套路由适合作为统一 API 接入样板,后续可以进一步扩展:
- 增加鉴权与签名校验
- 增加 JSON 字段提取与动态路由
- 增加异常处理与标准错误响应封装