Apache Camel使用消息的子字符串进行处理

时间:2014-12-02 15:51:38

标签: apache-camel

我想构建一个执行3个HttpRequests的Camel路由,但在每个请求中它只应该是正文的一部分。

在我的Message Body中是这个XML:

<part1>
...
</part1>
<part2>
...
</part2>
<part3>
...
</part3>

现在每个Part都应该发送到REST服务。 Rest-Service响应了一些数据,这个数据我必须放在下一部分的正文中。我该如何解决这个问题?

路线应该是这样的:

from("activemq:inMsg")
 .setBody(xpath("//part1")).inOut("http4://localhost/workingPart1")
 .choice()
   .when()
     .replay().isEqual("ok")
     .setBody("<responsePart1>"+replay()+"</responsePart1>" + xpath("//part2")).inOut("http4://localhost/workingPart2")
     .choice()
        .when()
          .replay().isEqual("ok")
          .setBody("<responsePart2>"+replay()+"</responsePart2>" + xpath("//part3")).inOut("http4://localhost/workingPart3")
        .otherwiese().to("activemq:error")
     .end()
  .otherwiese().to("activemq:error")
  .end()

你能帮我找到正确的语法吗?

谢谢

1 个答案:

答案 0 :(得分:1)

我想有不止一种可能的解决方案:

ModelCamelContext context = new DefaultCamelContext();
context.addRoutes(new RestBuilder("direct:rest1", "http4://localhost/workingPart1"));
context.addRoutes(new RestBuilder("direct:rest2", "http4://localhost/workingPart2"));
context.addRoutes(new RestBuilder("direct:rest3", "http4://localhost/workingPart3"));
context.addRoutes(new MainRouteBuilder());

ProducerTemplate template = context.createProducerTemplate();
template.sendBody("direct:start", XML);

RestBuilder类:

public class RestBuilder extends RouteBuilder {
    private final String endpoint;
    private final String uri;
    public RestBuilder(final String endpoint, final String uri) {
        this.endpoint = endpoint;
        this.uri = uri;
    }
    @Override
    public void configure() {
        from(endpoint)
            .setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http4.HttpMethods.POST))
            .to(uri)
            .choice()
            .when(header(Exchange.HTTP_RESPONSE_CODE).isNotEqualTo(Integer.valueOf(200)))
            .throwException(new IllegalStateException());
    }
}

MainRouteBuilder类:

public class MainRouteBuilder extends RouteBuilder {
    @Override
    public void configure() {
        onException(IllegalStateException.class)
            .log("Hm, no good")
            .to("activemq:error")
            .handled(true);

        from("direct:start")
            .setProperty("part1").xpath("/parts/part1/*")
            .setProperty("part2").xpath("/parts/part2/*")
            .setProperty("part3").xpath("/parts/part3/*")
            .setBody(simple("${property.part1}"))
            .to("direct:rest1")
            .setBody(simple("<responsePart1>${body}</responsePart1>${property.part2}"))
            .to("direct:rest2")
            .setBody(simple("<responsePart2>${body}</responsePart2>${property.part3}"))
            .to("direct:rest3");

    }
}