Apache Camel – 在启动时触发任务仅运行一次

我正在使用Camel和Spring开发Java项目。 我们想在Spring完成它的事情并且Camel完成构建所有路由之后在单例bean上触发初始化方法。

我们不能在类创建时调用该方法,因为它与从@Component spring注释中获取的其他类具有动态链接,并且我们不知道何时/是否已经加载这些类以实际运行init方法作为a的一部分构造函数。

如何在Camel启动完成后立即调用一个或多个方法来运行?

谢谢!

如果在CamelContext启动所有路由等之后必须调用bean,那么你可以像Ben建议使用带有计时器的路由。

一个更好的选择是使用Camel的EventNotifier API。 然后调用被触发的CamelContextStartedEvent上的逻辑。 有关EventNotifier API的一些详细信息,请访问: http : //camel.apache.org/eventnotifier-to-log-details-about-all-sent-exchanges.html

另一个提供更多灵活性的简单选项是使用带有repeatCount = 1的camel-timer和一个足够长的延迟值来让所有内容初始化。 你也可以添加基本的exception处理来延迟/重试等…

from("timer://runOnce?repeatCount=1&delay=5000").to("bean:runOnceBean"); 

一种解决方案是修补几个文件(参见PR https://github.com/apache/camel/pull/684):CamelContextConfiguration.java和RoutesCollector.java。

在CamelContextConfiguration中,添加方法:

 void afterApplicationStart(CamelContext camelContext); 

onApplicationEventRoutesCollector添加如下内容:

  if (camelContextConfigurations != null) { for (CamelContextConfiguration camelContextConfiguration : camelContextConfigurations) { camelContextConfiguration.afterApplicationStart(camelContext); } } 

如果使用截止日期的最新版本,您可以省略if (camelContextConfigurations != null)

然后按如下所示创建一个Spring bean来添加你的代码:

 @Bean CamelContextConfiguration contextConfiguration() { return new CamelContextConfiguration() { @Override public void beforeApplicationStart(CamelContext camelContext) { } @Override public void afterApplicationStart(CamelContext camelContext) { // Put your code here } }; } 

更新:此拉取请求已合并。

在bean的方法中添加逻辑并使用@PostConstruct对其进行注释 – 一旦完全初始化此bean并设置了所有依赖项,spring将调用此方法。

 @Component class SomeClass { @PostConstruct void init() { } } 

如果整个spring应用程序上下文完全初始化后需要调用逻辑,则可以通过实现LifeCycle接口来实现。

您可以尝试将camel上下文注入到单例bean中。 在上下文完全初始化之前不会发生注入…包括构建所有路径。 缺点是您可能实际上不需要bean中的上下文。 我想在将单例bean依赖关系链接到spring配置文件中的camelContext初始化,但是不确定它是否真的有效。

就像在答案之前已经暗示过这是一个spring而不是骆驼问题。 在Spring中,您可以简单地实现InitializingBean并实现menthod AfterPropertiesSet。 接线完成后调用。

您可以使用http://camel.apache.org/configuring-route-startup-ordering-and-autostartup.html中记录的Camel中的启动顺序function: –

             

具有startupOrder属性的路由将按顺序执行,并且所有路径都没有startupOrder。 因此,您可以在路线开始之前或之后使用您喜欢的计时器消费者路线。