Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am working on a Java project using Camel & Spring. We would like to trigger an initialize method on a singleton bean after Spring finished doing its thing and Camel has finished building all routes.

We cant call the method at class creation time as it has dynamic linkings to other classes that it picks up from the @Component spring annotation and we dont know when/if these classes have been loaded yet to actually run the init method as part of a constructor.

How can I go about invoking a method or methods to run only once right after Camel startup is complete?

Thanks!

like image 203
NightWolf Avatar asked Oct 10 '11 14:10

NightWolf


People also ask

What is direct start in Apache Camel?

direct:start provides synchronous ways to communicate between 2 endpoints and this is only been used if you want to communicate using camel messages and not generic file or xml messages. Save this answer.

What is InOnly in Camel?

InOnly — A one-way message (also known as an Event message). For example, JMS messaging is often one-way messaging. InOut — A request-response message.

What is Camel spring boot starter?

Spring Boot component provides auto-configuration for Apache Camel. Our opinionated auto-configuration of the Camel context auto-detects Camel routes available in the Spring context and registers the key Camel utilities (like producer template, consumer template and the type converter) as beans.

How do you start a Camel context?

CamelContext context = new DefaultCamelContext(); try { context. addRoutes(new RouteBuilder() { // Configure filters and routes } } ); The DefaultCamelContext class provides a concrete implementation of CamelContext. In addRoutes method, we create an anonymous instance of RouteBuilder.


2 Answers

another simple option which gives you a little more flexibility is to use camel-timer with a repeatCount=1 and a delay value long enough to let everything initialize. you can also add basic exception handling to delay/retry, etc...

from("timer://runOnce?repeatCount=1&delay=5000").to("bean:runOnceBean");
like image 86
Ben ODay Avatar answered Sep 30 '22 01:09

Ben ODay


If the bean must be invoked after CamelContext has started all the routes etc, then you can as Ben suggest use a route with a timer.

A possible better alternative is to use the EventNotifier API from Camel. And then invoke the logic on the CamelContextStartedEvent being fired. Some details on the EventNotifier API here: http://camel.apache.org/eventnotifier-to-log-details-about-all-sent-exchanges.html

like image 37
Claus Ibsen Avatar answered Sep 30 '22 01:09

Claus Ibsen