首页 > 解决方案 > Camel 的 endChoice():有什么意义?(不是与 end() 的区别)

问题描述

我在这里发现了 2 个问题,询问 Camel 的 .end() 和 .endChoice() 之间的区别。这对我来说不是问题。我很清楚 .end() 用于完成 .choice() 块,而 .endChoice() 用于完成 .when() 块。

但是,我的问题是……毕竟,使用 .endChoice()s 有什么意义?仅仅是为了让代码更清晰吗?

看看这些例子(请不要指出这个的正确性或可用性,我的意思是理解机制,而不是要求干净的代码模型):

代码示例 1:

from("file:files/input")
            .choice()
                .when(simple("${file:ext} ends with 'xml'"))
                    .log("LOG 1")
                    .choice()
                        .when(simple("${file:ext} ends with 'xml'"))
                            .log("LOG 1 nested")
                        .endChoice()
                        .when(simple("${file:ext} ends with 'xml'"))
                            .log("LOG 2 nested")
                        .endChoice()
                .endChoice()
                .when(simple("${file:ext} ends with 'xml'"))
                    .log("LOG 2")
                .endChoice()
                .otherwise()
                    .log("NOT AN XML FILE")
            .end().to("file:files/output");

代码示例 2:

from("file:files/input")
            .choice()
                .when(simple("${file:ext} ends with 'xml'"))
                    .log("LOG 1")
                    .choice()
                        .when(simple("${file:ext} ends with 'xml'"))
                            .log("LOG 1 nested")
                        .when(simple("${file:ext} ends with 'xml'"))
                            .log("LOG 2 nested")
                .when(simple("${file:ext} ends with 'xml'"))
                    .log("LOG 2")
                .otherwise()
                    .log("NOT AN XML FILE")
            .end().to("file:files/output");

我测试了将 xml 文件放在文件夹中,两个代码都做同样的事情。无论你是否使用 .endChoice()s,.when()s 总是表现得像“elseif”语句,也就是说,响应是“LOG 1”和“LOG1 nested”,“LOG2”和“LOG 2 nested” “从不打印。如果文件不是 xml,则按预期触发否则路由。

希望我问的很清楚。此致。

标签: javaapache-camelspring-camel

解决方案


.endChoice只是补偿有关 Camel DSL 限制的一种解决方法

您的示例工作正常,因为您的when 块有一个非常简单的内容。如果您将更复杂的 EIP 放入其中,您可能会遇到没有.endChoice.

看看骆驼网站上的这个例子就是这样一个案例。

我也有一些罕见的情况甚至.endChoice没有帮助。但通常在这种情况下,路由无论如何都太复杂了,应该拆分


推荐阅读