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

为什么Spring DSL中Apache Camel路由to的url参数无法插入header值

问题原因

Apache Camel 中标准的 <to> 组件的 URI 会在路由初始化阶段完成静态解析,不会在每条消息的运行时处理阶段对 URI 内的 Simple 表达式(即${header.kafka.KEY}语法)做动态替换。而 <log> 组件的 message 属性默认支持运行时解析 Simple 表达式,所以日志可以正确输出 header 取值,发送 MQTT 时主题就变成了字面量字符串。

解决方案

使用 Camel 提供的动态发送组件 <toD> 替换原有的静态 <to> 标签即可,<toD> 会在每条消息处理时动态计算 URI 中的表达式,读取当前消息的 header 拼接为正确的主题名。

修改后的路由配置如下:

<routes
    xmlns="http://camel.apache.org/schema/spring">
    <route id="KafkaToMQTT">
        <from uri="kafka://mqtt?brokers=localhost:9092"/>
        <to uri="micrometer:timer:camel.proxy.kafka.mqtt.stream?action=start"/>
        <log message="Headers ${header.kafka.KEY}"/>
        <!-- 把to替换为toD -->
        <toD uri="mqtt:mqtt?host=tcp://localhost:1883&amp;publishTopicName=try${header.kafka.KEY}"/>
        <to uri="log://camel.proxy?groupInterval=3&amp;level=INFO"/>
        <to uri="micrometer:timer:camel.proxy.kafka.mqtt.stream?action=stop"/>      
    </route>
</routes>

如果使用的是 2.16 之前不支持 <toD> 的旧版本 Camel,可以用 <recipientList> 实现相同效果:

<recipientList>
    <simple>mqtt:mqtt?host=tcp://localhost:1883&amp;publishTopicName=try${header.kafka.KEY}</simple>
</recipientList>

内容的提问来源于stack exchange,提问作者Eljah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:45:03