在Apache Camel中切换外壳

and*_*Pat 3 java apache-camel

Apache Camel(在Java DSL中)是否有类似于Java交换器的构造?

例如:

 from( incomingRoute )
    .choice()
    .when( simple( "${body.getType} == '" + TYPE.A.name() + "'" ) )
                .to( A_Endpoint )
    .when( simple( "${body.getType} == '" + TYPE.B.name() + "'" ) )
                .to( B_Endpoint )
    .when( simple( "${body.getType} == '" + TYPE.C.name() + "'" ) )
                .to( C_Endpoint )
   .otherwise()
                .to( errorEndpoint );
Run Code Online (Sandbox Code Playgroud)

可以翻译成其他更类似于switch的东西吗?我的意思是我不想使用简单的谓词,而只使用body元素类型的值。还是我的方法完全错误?(这可能是合理的)

Mil*_*vić 5

我通常更喜欢在特定情况下使用Java 8 lambda:

public void configure() throws Exception {
  from( incomingRoute )
     .choice()
     .when( bodyTypeIs( TYPE.A ) )
                 .to( A_Endpoint )
     .when( bodyTypeIs(  TYPE.B ) )
                 .to( B_Endpoint )
     .when( bodyTypeIs(  TYPE.C ) )
                 .to( C_Endpoint )
     .otherwise()
                 .to( errorEndpoint );
}

private Predicate bodyTypeIs(TYPE type) {
  return e -> e.getIn().getBody(BodyType.class).getType() == type;
}
Run Code Online (Sandbox Code Playgroud)

此外,将Camel Predicate与Java 8结合使用可以构建一些很棒的流利的API,例如添加自己的函数类型Predicate

@FunctionalInterface
public interface ComposablePredicate extends Predicate, java.util.function.Predicate<Exchange> {

  @Override
  default boolean matches(Exchange exchange) {
    return test(exchange);
  }

  @Override
  default ComposablePredicate and(java.util.function.Predicate<? super Exchange> other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) && other.test(t);
  }

  @Override
  default ComposablePredicate negate() {
    return (t) -> !test(t);
  }

  @Override
  default ComposablePredicate or(java.util.function.Predicate<? super Exchange> other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) || other.test(t);
  }
}
Run Code Online (Sandbox Code Playgroud)

这使您可以编写如下内容:

public void configure() throws Exception {
  from( incomingRoute )
     .choice()
     .when( bodyTypeIs( TYPE.A ) .or ( bodyTypeIs( TYPE.A1 ) ) )
                 .to( A_Endpoint )
     .when( bodyTypeIs(  TYPE.B ).negate() )
                 .to( NOT_B_Endpoint )
     .when( bodyTypeIs(  TYPE.C ) .and ( bodyNameIs( "name" ) ) )
                 .to( C_Endpoint )
     .otherwise()
                 .to( errorEndpoint );
}

private ComposablePredicate bodyTypeIs(TYPE type) {
  return e -> bodyFrom(e).getType() == type;
}

private BodyType bodyFrom(Exchange e) {
  return e.getIn().getBody(BodyType.class);
}

private ComposablePredicate bodyNameIs(String name) {
  return e -> bodyFrom(e).getName().equals(name);
}
Run Code Online (Sandbox Code Playgroud)