gpt4 book ai didi

java - Apache Camel 中的开关盒

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:06:28 26 4
gpt4 key购买 nike

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 元素类型的值。还是我的方法完全错误? (这可能是合理的)

最佳答案

我通常更喜欢在特定场景中使用 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;
}

此外,在 Java 8 中使用 Camel 的 Predicate 可以实现一些非常流畅的 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);
}

关于java - Apache Camel 中的开关盒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39143545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com