骆驼 - 使用 end()

15

在每个路由中使用end()是最佳实践吗?

以下代码是有效的:

from("jms:some-queue")      
    .beanRef("bean1", "method1")
    .beanRef("bean2", "method2")

如此也是如此,

from("jms:some-queue")      
    .beanRef("bean1", "method1")
    .beanRef("bean2", "method2")
    .end()
2个回答

24

不要这样做! 调用 end() "结束" Camel 路由并不是最佳实践,也不会产生任何功能上的好处。

对于像to()bean()log()这样的常见的ProcessorDefinition函数,它只会导致调用endParent()方法,正如我们从Camel源代码中可以看到的那样,该方法做了很少的事情:

public ProcessorDefinition<?> endParent() { return this; }

在调用启动其自己的块的处理器定义后,需要调用end(),其中最突出的包括TryDefinitions(又名doTry())和ChoiceDefinitions(又名choice()),但也包括众所周知的函数,例如split(), loadBalance(), onCompletion()recipientList()


2
嗨,有没有一些文档可以解释一下end()方法?谢谢。 - Hector
嗨,我没有找到关于end()方法的官方文档,但我认为以下链接足以证实答案:camel users: question about end() - the hand of NOD

8

当你想结束正在进行的特定路由时,必须使用end()。最好通过onCompletion的示例来解释。

from("direct:start")
.onCompletion()
    // this route is only invoked when the original route is complete as a kind
    // of completion callback
    .to("log:sync")
    .to("mock:sync")
// must use end to denote the end of the onCompletion route
.end()
// here the original route contiues
.process(new MyProcessor())
.to("mock:result");

在这里,您必须放置“end”以表示与onCompletion相关的操作已完成,并且您正在恢复对原始路由的操作。

如果您使用XML DSL而不是Java,则此内容变得更加清晰易懂。因为在这种情况下,您不必使用结束标记。 XML的关闭标记将负责编写end()。以下是完全相同的示例,用XML DSL编写:

<route>
<from uri="direct:start"/>
<!-- this onCompletion block will only be executed when the exchange is done being routed -->
<!-- this callback is always triggered even if the exchange failed -->
<onCompletion>
    <!-- so this is a kinda like an after completion callback -->
    <to uri="log:sync"/>
    <to uri="mock:sync"/>
</onCompletion>
<process ref="myProcessor"/>
<to uri="mock:result"/>


谢谢,我明白有些情况下我们必须使用end()(否则可能会导致编译错误)。我的疑问是,在我提出的情况下,这是否有任何区别? - saravana_pc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接