问题
I'm trying to add an EventNotifier to my Apache Camel standalone application which uses the Main class from Camel.
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();
}
I want to add an EventNotifier like in this cookbook example:
http://camel.apache.org/eventnotifier-to-log-details-about-all-sent-exchanges.html
Here is my simple EventNotifier
@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;
}
Using Java DSL, I want to do something like:
context.getManagementStrategy().addEventNotifier(new MyEventNotifier());
There are a few methods on Main that seems like they would be helpful: main.getOrCreateCamelContext() and main.getCamelContexts().
getOrCreateCamelContext will create a context but when main.run() is called, that context goes away (Camel-1 and is the only context but after main.run(), Camel-2 is the only context).
getCamelContexts is empty until main.run() is called.
I tried adding the EventNotifier in another thread after the context is created by Main but nothing shows in my log so I suspect the EventNotifier needs to be added before the context is started.
Is there an easy way to do that?
回答1:
I found one way: create an anonymous inner class and override the postProcessCamelContext method.
Main main = new Main() {
@Override
protected void postProcessCamelContext(CamelContext camelContext) throws Exception {
super.postProcessCamelContext(camelContext);
camelContext.getManagementStrategy().addEventNotifier(new MyEventNotifier());
}
};
来源:https://stackoverflow.com/questions/30354698/how-to-add-an-eventnotifier-to-camel-using-main-class-standalone