Camel Java DSL Route with Choice 仅针对最后一个条件进行

jak*_*aks 3 java apache-camel

我有很多选择,但这条路线只适用于最后一个条件。对于其他情况,路线被卡住,不会继续前进。

public class CamelChoiceTest {

  private CamelContext context;

  @Before
  public void initializeContext() throws Exception {

    RouteBuilder builder = new RouteBuilder() {
      public void configure() {

        from("direct:test")
          .choice()
            .when(header("number").isEqualTo("one")).to("direct:one")
            .when(header("number").isEqualTo("two")).to("direct:two")
            .when(header("number").isEqualTo("three")).to("direct:three")
          .endChoice()
          .log("only final condition reaches here");

        from("direct:one").log("one is selected");
        from("direct:two").log("two is selected");
        from("direct:three").log("three is selected");
      }
    };

    context = new DefaultCamelContext();
    context.addRoutes(builder);
    context.setTracing(true);
    context.start();
  }

  private void send(String header){
    Exchange exchange = new DefaultExchange(context);
    exchange.getIn().setHeader("number", header);
    exchange.getIn().setBody("test", String.class);
    ProducerTemplate producerTemplate = context.createProducerTemplate();
    // Send the request
    producerTemplate.send("direct:test", exchange);
  }

  @Test
  public void testOne() throws Exception {
    send("one");
  }

  @Test
  public void testTwo() throws Exception {
    send("two");
  }

  @Test
  public void testThree() throws Exception {
    send("three");
  }
}
Run Code Online (Sandbox Code Playgroud)

执行时,将打印日志“仅最终条件到达此处”作为最终条件。当条件也重新排序时,它将打印最后一个条件。

我认为这是 Java DSL 的问题。当我在 XML 中创建相同的内容时,它工作正常,

<camel:camelContext id="testCamelContext" trace="true"
        streamCache="true">
        <camel:route>
            <camel:from uri="direct:test" />
            <camel:choice>
                <camel:when>
                    <camel:simple>${header.number} == 'one'</camel:simple>
                    <camel:to uri="direct:one" />
                </camel:when>
        <camel:when>
          <camel:simple>${header.number} == 'two'</camel:simple>
          <camel:to uri="direct:two" />
        </camel:when>
        <camel:when>
          <camel:simple>${header.number} == 'three'</camel:simple>
          <camel:to uri="direct:three" />
        </camel:when>
            </camel:choice>
            <camel:to uri="bean:routeBean?method=receive" />
        </camel:route>
    </camel:camelContext>
Run Code Online (Sandbox Code Playgroud)

Pet*_*ler 5

在您的示例中,when条件似乎正确评估,但是测试“一”和“二”缺少最终日志语句。

使用.end()代替.endCoice()

  • 使用.endChoice()以返回“回”到基于内容的路由器,即使用.endChoice()结束一个when条件,如果代码块并不是一个简单的声明,请参阅这里有关此问题的详细信息。
  • 使用.end()以结束整个choice块。