10.3. 规范化程序

概述

规范化程序 模式用于处理语义等同的信息,但采用不同格式。规范化程序将传入的信息转换为常见格式。

在 Apache Camel 中,您可以合并 第 8.1 节 “基于内容的路由器” 来实现规范化程序模式,它检测到传入的消息的格式,使用不同的 第 5.6 节 “message Translator” 集合,它会将不同的传入的格式转换为常见格式。

图 10.3. 规范化程序模式

规范化程序模式

Java DSL 示例

本例演示了 Message Normalizer,它将两种 XML 消息转换为常见格式。然后会过滤此通用格式的消息。

使用 Fluent Builders

// 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"/>