Camel 的endChoice():这有什么意义?(与end()没有区别)

1tuwyuhd  于 2022-11-07  发布在  Apache
关注(0)|答案(1)|浏览(263)

我在这里发现了两个问题,询问Camel的.end()和.endChoice()之间的区别。这对我来说不是问题。对我来说很清楚,.end()用于完成.choice()块,而.endChoice()用于完成.when()块。
然而,我的问题是......到底使用.endChoice()有什么意义呢?仅仅是为了让代码更清晰吗?
看看这些例子(请不要指出它的正确性或可用性,我在这里的重点是理解机制,而不是要求干净的代码模型):
代码示例1:

  1. from("file:files/input")
  2. .choice()
  3. .when(simple("${file:ext} ends with 'xml'"))
  4. .log("LOG 1")
  5. .choice()
  6. .when(simple("${file:ext} ends with 'xml'"))
  7. .log("LOG 1 nested")
  8. .endChoice()
  9. .when(simple("${file:ext} ends with 'xml'"))
  10. .log("LOG 2 nested")
  11. .endChoice()
  12. .endChoice()
  13. .when(simple("${file:ext} ends with 'xml'"))
  14. .log("LOG 2")
  15. .endChoice()
  16. .otherwise()
  17. .log("NOT AN XML FILE")
  18. .end().to("file:files/output");

代码示例2:

  1. from("file:files/input")
  2. .choice()
  3. .when(simple("${file:ext} ends with 'xml'"))
  4. .log("LOG 1")
  5. .choice()
  6. .when(simple("${file:ext} ends with 'xml'"))
  7. .log("LOG 1 nested")
  8. .when(simple("${file:ext} ends with 'xml'"))
  9. .log("LOG 2 nested")
  10. .when(simple("${file:ext} ends with 'xml'"))
  11. .log("LOG 2")
  12. .otherwise()
  13. .log("NOT AN XML FILE")
  14. .end().to("file:files/output");

我测试了将xml文件放到files文件夹中,两个代码做的事情完全相同。无论是否使用.endChoice()s,.when()s总是表现为“elseif”语句,即响应是“LOG 1”和“LOG1 nested”,而“LOG2”和“LOG 2 nested”永远不会打印。如果文件不是xml,则会按预期触发其他路由。
希望我问的是清楚的。最好的问候。

fdx2calv

fdx2calv1#

.endChoice只是弥补Camel DSL限制的一种解决方法。
您的示例运行良好,因为您的when块的内容非常简单。如果您将更复杂的EIP放入其中,您可能会遇到这样的情况:如果没有.endChoice,您的代码将无法编译。
请看thisexample on the Camel website中的例子。
我也遇到过.endChoice也不起作用的情况,但通常在这种情况下,路径太复杂了,应该被拆分

相关问题