10.3. 规范化程序
概述
规范化程序 模式用于处理以语义等同性的消息,但会采用不同的格式。规范化程序将传入的消息转换为常见格式。
在 Apache Camel 中,您可以通过组合 第 8.1 节 “基于内容的路由器” 来实现规范化程序模式,它可检测进入消息的格式,使用不同的 第 5.6 节 “消息转换器” 集,它会将不同的传入格式转换为常见格式。
图 10.3. 规范化模式

Java DSL 示例
本例演示了一个 Message Normalizer,它将两种类型的 XML 消息转换为通用格式。然后,会过滤采用这种通用格式的消息。
// we need to normalize two types of incoming messages
from("direct:start")
.choice()
.when().xpath("/employee").to("bean:normalizer?method=employeeToPerson")
.when().xpath("/customer").to("bean:normalizer?method=customerToPerson")
.end()
.to("mock:result");在这种情况下,我们使用 Java Bean 作为规范化程序。类如下所示
// Java
public class MyNormalizer {
public void employeeToPerson(Exchange exchange, @XPath("/employee/name/text()") String name) {
exchange.getOut().setBody(createPerson(name));
}
public void customerToPerson(Exchange exchange, @XPath("/customer/@name") String name) {
exchange.getOut().setBody(createPerson(name));
}
private String createPerson(String name) {
return "<person name=\"" + name + "\"/>";
}
}XML 配置示例
XML DSL 中的相同示例
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start"/>
<choice>
<when>
<xpath>/employee</xpath>
<to uri="bean:normalizer?method=employeeToPerson"/>
</when>
<when>
<xpath>/customer</xpath>
<to uri="bean:normalizer?method=customerToPerson"/>
</when>
</choice>
<to uri="mock:result"/>
</route>
</camelContext>
<bean id="normalizer" class="org.apache.camel.processor.MyNormalizer"/>