在Apache Camel中切换案例

时间:2016-08-25 11:03:25

标签: java apache-camel

Apache Camel(在Java DSL中)是否有类似于Java switch-case的构造?

例如:

 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 );

可以翻译成更类似于switch的其他内容吗?我的意思是我不想使用简单谓词,只需要使用body元素类型的值。 或者我的做法完全错了? (这可能是合理的)

1 个答案:

答案 0 :(得分:4)

我通常更喜欢在特定场景中使用Java 8 lambdas:

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;
}

此外,使用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);
  }
}

允许你写下这样的东西:

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);
}
相关问题