So in your Java code you can do
Notice in Camel 2.0 we have introduced the
There are 3 main polling methods on PollingConsumer
Waits until a message is available and then returns it; potentially blocking forever
Attempts to receive a message exchange, waiting up to the given timeout and returning null if no message exchange could be received within the time available
Attempts to receive a message exchange immediately without waiting and returning null if a message exchange is not available yet
Available as of Camel 2.0
The template supports the 3 operations above, but also including convenient methods for returning the body, etc
The example from above using ConsumerTemplate is:
Or to extract and get the body you can do:
And you can provide the body type as a parameter and have it returned as the type:
You get hold of a
ConsumerTemplate from the
CamelContext with the
Using ConsumerTemplate with Spring DSL
With the Spring DSL we can declare the consumer in the CamelContext with the consumerTemplate tag, just like the ProducerTemplate. The example below illustrates this:
Then we can get leverage Spring to inject the
ConsumerTemplate in our java class. The code below is part of an unit test but it shows how the consumer and producer can work together.
Timer based polling consumer
In this sample we use a Timer to schedule a route to be started every 5th second and invoke our bean MyCoolBean where we implement the business logic for the Polling Consumer. Here we want to consume all messages from a JMS queue, process the message and send them to the next queue.
First we setup our route as:
And then we have out logic in our bean:
Scheduled Poll Components
Quite a few inbound Camel endpoints use a scheduled poll pattern to receive messages and push them through the Camel processing routes. That is to say externally from the client the endpoint appears to use an Event Driven Consumer but internally a scheduled poll is used to monitor some kind of state or resource and then fire message exchanges.
Since this a such a common pattern, polling components can extend the ScheduledPollConsumer base class which makes it simpler to implement this pattern.
There is also the Quartz Component which provides scheduled delivery of messages using the Quartz enterprise scheduler.
For more details see