how to implement an event-drive consumer in camel

apache-camel, java

Solution

Event driven is what camel is.

Any route is actually an event listener.

given the route:

from("activemq:SomeQueue").
  bean(MyClass.class);

public class MyBean{
  public void handleEvent(MyEventObject eventPayload){ // Given MyEventObject was sent to this "SomeQueue".
     // whatever processing.
  }
}

That would put up an event driven consumer. How to send events then? If you have camel embedded in your app and access to the CamelContext from your event action generator, then you could grab a Producer Template from it and just fire of your event to whatever endpoint you defined in Camel, such as "seda:SomeQueue".

Otherwise, if your Camel instance is running in another server or instance than your application, then you should use some other transport rather than SEDA. Preferably JMS, but others will do as well, pick and choose. ActiveMQ is my favourite. You can start an embedded activemq instance (intra JVM) easily and connect it to camel by:

camelContext.addComponent("activemq", activeMQComponent("vm://localhost"));

Problem

I am very new to Camel, and have been struggling to understand how to use camel in a specific scenario. In this scenario, there is a (Java-based) agent that generates actions from time to time. I need an event-driven consumer to get notified of these events. These events will be routed to a 'file' producer (for the time being). In the camel book, the example is for a polling consumer. I could not find a generic solution for an event-driven consumer. I came across a similar implementation for JMX : ``` public class JMXConsumer extends DefaultConsumer implements NotificationListener { JMXEndpoint jmxEndpoint; public JMXConsumer(JMXEndpoint endpoint, Processor processor) { super(endpoint, processor); this.jmxEndpoint = endpoint; } public void handleNotification(Notification notification, Object handback) { try { getProcessor().process(jmxEndpoint.createExchange(notification)); } catch (Throwable e) { handleException(e); } } ``` } Here, the handleNotification is invoked whenever a JMX notification arrives. I believe I have to do something similar to get my consumer notified whenever the agent generates an action. However, the above handleNotification method is specific to JMX. The web page says: " When implementing your own event-driven consumer, you must identify an analogous event listener method to implement in your custom consumer." I want to know: How can I identify an analogous event listener, so that my consumer will be notified whenever my agent has an action. Any advice/link to a web page is very much appreciated.

Original source