为什么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&publishTopicName=try${header.kafka.KEY}"/> <to uri="log://camel.proxy?groupInterval=3&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&publishTopicName=try${header.kafka.KEY}</simple> </recipientList>
内容的提问来源于stack exchange,提问作者Eljah
相关产品推荐
相关产品推荐

