簡體   English   中英

Apache Camel - 在啟動時觸發任務僅運行一次

[英]Apache Camel - Triggering a task on startup to run only once

我正在使用Camel&Spring開發Java項目。 我們想在Spring完成它的事情並且Camel已經完成所有路由的構建之后在單例bean上觸發初始化方法。

我們不能在類創建時調用該方法,因為它與從@Component spring注釋中獲取的其他類具有動態鏈接,並且我們不知道何時/是否已經加載這些類以實際運行init方法作為a的一部分構造函數。

如何在Camel啟動完成后立即調用一個或多個方法來運行?

謝謝!

另一個提供更多靈活性的簡單選項是使用帶有repeatCount = 1的camel-timer和一個足夠長的延遲值來讓所有內容初始化。 你還可以添加基本的異常處理來延遲/重試等...

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

如果在CamelContext啟動所有路由等之后必須調用bean,那么你可以像Ben建議使用帶有計時器的路由。

一個更好的選擇是使用Camel的EventNotifier API。 然后調用被觸發的CamelContextStartedEvent上的邏輯。 有關EventNotifier API的一些詳細信息,請訪問: http//camel.apache.org/eventnotifier-to-log-details-about-all-sent-exchanges.html

一種解決方案是修補幾個文件(參見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接口來實現。

您可以使用http://camel.apache.org/configuring-route-startup-ordering-and-autostartup.html中記錄的Camel中的啟動順序功能: -

<route startupOrder="1" id="thisOneGoesFirst">    
  <from uri="seda:foo"/>
  <to uri="mock:result"/>
</route>
<route startupOrder="2" id="thisOneGoesSecond">
  <from uri="direct:start"/>
  <to uri="seda:foo"/>
</route> 
<route id="thisOneGoesLast">
  <from uri="direct:bar"/>
  <to uri="seda:bar"/>
</route>

具有startupOrder屬性的路由將按順序執行,並且所有路徑都沒有startupOrder。 因此,您可以在路線開始之前或之后,使用您喜歡的定時器消費者路線。

您可以嘗試將camel上下文注入到單例bean中。 在上下文完全初始化之前不會發生注入...包括構建所有路徑。 缺點是您可能實際上不需要bean中的上下文。 我想知道將單例bean依賴關系鏈接到spring配置文件中的camelContext初始化,但是不確定它是否會真正起作用。

就像在答案之前已經暗示過這是一個春天而不是駱駝問題。 在Spring中,您可以簡單地實現InitializingBean並實現menthod AfterPropertiesSet。 接線完成后調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM