2015-05-20 21 views
1

我想添加一個EventNotifier到我的Apache Camel獨立應用程序使用駱駝的Main類。如何添加一個EventNotifier到駱駝使用主類獨立

http://camel.apache.org/running-camel-standalone-and-have-it-keep-running.html

public void boot() throws Exception { 
    Main main = new Main(); 
    main.addRouteBuilder(new MyRouteBuilder()); 
    System.out.println("Starting Camel. Use ctrl + c to terminate the JVM.\n"); 
    main.run(); 
} 

我想在這個食譜例如添加一個事件通知器,如:

http://camel.apache.org/eventnotifier-to-log-details-about-all-sent-exchanges.html

這裏是我的簡單的事件通知

@Override 
public void notify(EventObject event) throws Exception { 
    logger.info(event.toString()); 
} 

@Override 
public boolean isEnabled(EventObject event) { 
    logger.info("Checked if enabled"); 
    return true; 
} 

使用Java DSL,我想要做一些事情:

context.getManagementStrategy().addEventNotifier(new MyEventNotifier()); 

有上主要的幾個方法,這似乎是他們將是有益的:main.getOrCreateCamelContext()和main.getCamelContexts()。

getOrCreateCamelContext將創建上下文,但是當main.run()被調用時,該上下文消失(駱駝-1,並且是唯一上下文但main.run()後,駱駝-2是唯一的上下文) 。

getCamelContexts在調用main.run()之前爲空。

我嘗試在Main創建上下文後在另一個線程中添加EventNotifier,但沒有在我的日誌中顯示,因此我懷疑在上下文啓動之前需要添加EventNotifier。

有沒有簡單的方法來做到這一點?

回答

0

我找到了一種方法:創建一個匿名內部類並重寫postProcessCamelContext方法。

Main main = new Main() { 
     @Override 
     protected void postProcessCamelContext(CamelContext camelContext) throws Exception { 
      super.postProcessCamelContext(camelContext); 
      camelContext.getManagementStrategy().addEventNotifier(new MyEventNotifier()); 
     } 
    };