camel中filter和choice的区别

Difference between filter and choice in camel

apache Camel 中的 filter 和 choice 有什么区别?

    from("direct:a")
        .choice()
            .when(header("foo").isEqualTo("bar"))
                .to("direct:b")
            .when(header("foo").isEqualTo("cheese"))
                .to("direct:c")
            .otherwise()
                .to("direct:d");

此外,Choice 和 filter 执行相同的操作,其中 Filter 中有额外的 属性 Exchange 表示它是否被过滤。

  1. 从 2.0 版开始可以选择
  2. 过滤器从 2.5 版开始可用

简而言之,过滤器就像一个 java if 语句,例如

if x = 2 {
  ...
}

在骆驼中:

.filter(header("foo").isEqualTo("bar"))
  ...
.end()

选择就像一个java if ... elseif ... elseif ... else语句,

if x = 2 {
  ...
} else if x = 3 {
  ...
}

在骆驼中:

.choice()
  .when(header("foo").isEqualTo("bar"))
    ...
  .when(header("foo").isEqualTo("chese"))
    ...
  .otherwise()
    ....
.end()

请注意 otherwisechoice 中是可选的。