Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Wiki Markup
h3. Polling Consumer

Camel supports implementing the [Polling Consumer|http://www.enterpriseintegrationpatterns.com/PollingConsumer.html] from the [EIP patterns|Enterprise Integration Patterns] using the [PollingConsumer|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/PollingConsumer.html] interface which can be created via the [Endpoint.createPollingConsumer()|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Endpoint.html#createPollingConsumer()] method.

!http://www.enterpriseintegrationpatterns.com/img/PollingConsumerSolution.gif!

So in your Java code you can do

{code}
Endpoint endpoint = context.getEndpoint("activemq:my.queue");
PollingConsumer consumer = endpoint.createPollingConsumer();
Exchange exchange = consumer.receive();
{code}

The {{ConsumerTemplate}} (discussed below) is also available.

There are 3 main polling methods on [PollingConsumer|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/PollingConsumer.html]

|| Method name || Description ||
| [receive()|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/PollingConsumer.html#receive()] | Waits until a message is available and then returns it; potentially blocking forever |
| [receive(long)|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/PollingConsumer.html#receive(long)] | 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 |
| [receiveNoWait()|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/PollingConsumer.html#receiveNoWait()] | Attempts to receive a message exchange immediately without waiting and returning null if a message exchange is not available yet |

h3. ConsumerTemplate

The {{ConsumerTemplate}} is a template much like Spring's JmsTemplate or JdbcTemplate supporting the [Polling Consumer] EIP. With the template you can consume [Exchange]s from an [Endpoint].

The template supports the 3 operations above, but also including convenient methods for returning the body, etc {{consumeBody}}.
The example from above using ConsumerTemplate is:
{code}
Exchange exchange = consumerTemplate.receive("activemq:my.queue");
{code}
Or to extract and get the body you can do:
{code}
Object body = consumerTemplate.receiveBody("activemq:my.queue");
{code}
And you can provide the body type as a parameter and have it returned as the type:
{code}
String body = consumerTemplate.receiveBody("activemq:my.queue", String.class);
{code}
You get hold of a {{ConsumerTemplate}} from the {{CamelContext}} with the {{createConsumerTemplate}} operation:
{code}
ConsumerTemplate consumer = context.createConsumerTemplate();
{code}

h4. 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:
{snippet:id=e1|lang=xml|url=camel/trunk/components/camel-spring/src/test/resources/org/apache/camel/spring/SpringConsumerTemplateTest-context.xml}

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. 
{snippet:id=e1|lang=java|url=camel/trunk/components/camel-spring/src/test/java/org/apache/camel/spring/SpringConsumerTemplateTest.java}

h4. 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:
{snippet:id=e1|lang=java|url=camel/tags/camel-2.6.0/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsTimerBasedPollingConsumerTest.java}

And then we have out logic in our bean:
{snippet:id=e2|lang=java|url=camel/tags/camel-2.6.0/components/camel-jms/src/test/java/org/apache/camel/component/jms/JmsTimerBasedPollingConsumerTest.java}


h3. 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|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/ScheduledPollConsumer.html] base class which makes it simpler to implement this pattern.

There is also the [Quartz Component|Quartz] which provides scheduled delivery of messages using the Quartz enterprise scheduler.

For more details see:

* [PollingConsumer|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/PollingConsumer.html]
* Scheduled Polling Components
** [ScheduledPollConsumer|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/ScheduledPollConsumer.html]
** [Atom]
** [File|File2]
** [FTP|FTP2]
** [hbase|HBase]
** [iBatis]
** [JPA]
** [Mail]
** [MyBatis]
** [Quartz]
** [SNMP]
** [AWS-S3|AWS-S3]
** [AWS-SQS|AWS-SQS]

h3. ScheduledPollConsumer Options
The ScheduledPollConsumer supports the following options:

{div:class=confluenceTableSmall}
|| Option || Default || Description ||
| {{pollStrategy}} | - | A pluggable {{org.apache.camel.PollingConsumerPollStrategyPollingConsumerPollingStrategy}} allowing you to provide your custom implementation to control error handling usually occurred during the {{poll}} operation *before* an [Exchange] have been created and being routed in Camel. In other words the error occurred while the polling was gathering information, for instance access to a file network failed so Camel cannot access it to scan for files. The default implementation will log the caused exception at {{WARN}} level and ignore it. |
| {{sendEmptyMessageWhenIdle}} | {{false}} | *Camel 2.9:* If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. |
| {{startScheduler}} | {{true}} | Whether the scheduler should be auto started. |
| {{initialDelay}} | {{1000}} | Milliseconds before the first poll starts. |
| {{delay}} | {{500}} | Milliseconds before the next poll. |
| {{useFixedDelay}} |  | Controls if fixed delay or fixed rate is used. See [ScheduledExecutorService|http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html] in JDK for details. In *Camel 2.7.x* or older the default value is {{false}}. From *Camel 2.8* onwards the default value is {{true}}. |
| timeUnit | {{TimeUnit.MILLISECONDS}} | time unit for {{initialDelay}} and {{delay}} options. |
| {{runLoggingLevel}} | {{TRACE}} | *Camel 2.8:* The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. |
| {{scheduledExecutorService}} | {{null}} | *Camel 2.10:* Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. This option allows you to share a thread pool among multiple consumers. |
{div}

h3. About error handling and scheduled polling consumers
[ScheduledPollConsumer|http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/ScheduledPollConsumer.html] is scheduled based and its {{run}} method is invoked periodically based on schedule settings. But errors can also occur when a poll is being executed. For instance if Camel should poll a file network, and this network resource is not available then a {{java.io.IOException}} could occur. As this error happens *before* any [Exchange] has been created and prepared for routing, then the regular [Error handling in Camel] does not apply. So what does the consumer do then? Well the exception is propagated back to the {{run}} method where its handled. Camel will by default log the exception at {{WARN}} level and then ignore it. At next schedule the error could have been resolved and thus being able to poll the endpoint successfully.

h4. Controlling the error handling using PollingConsumerPollStrategy

{{org.apache.camel.PollingConsumerPollStrategy}} is a pluggable strategy that you can configure on the {{ScheduledPollConsumer}}. The default implementation {{org.apache.camel.impl.DefaultPollingConsumerPollStrategy}} will log the caused exception at {{WARN}} level and then ignore this issue.

The strategy interface provides the following 3 methods
- begin
-- {{void begin(Consumer consumer, Endpoint endpoint)}}
- begin (*Camel 2.3*)
-- {{boolean begin(Consumer consumer, Endpoint endpoint)}}
- commit
-- {{void commit(Consumer consumer, Endpoint endpoint)}}
- commit (*Camel 2.6*)
-- {{void commit(Consumer consumer, Endpoint endpoint, int polledMessages)}}
- rollback
-- {{boolean rollback(Consumer consumer, Endpoint endpoint, int retryCounter, Exception e) throws Exception}}

In *Camel 2.3* onwards the begin method returns a boolean which indicates whether or not to skipping polling. So you can implement your custom logic and return {{false}} if you do not want to poll this time.

In *Camel 2.6* onwards the commit method has an additional parameter containing the number of message that was actually polled. For example if there was no messages polled, the value would be zero, and you can react accordingly.

The most interesting is the {{rollback}} as it allows you do handle the caused exception and decide what to do. 

For instance if we want to provide a retry feature to a scheduled consumer we can implement the {{PollingConsumerPollStrategy}} method and put the retry logic in the {{rollback}} method. Lets just retry up till 3 times:
{code:java}
    public boolean rollback(Consumer consumer, Endpoint endpoint, int retryCounter, Exception e) throws Exception {
        if (retryCounter < 3) {
            // return true to tell Camel that it should retry the poll immediately
            return true;
        }
        // okay we give up do not retry anymore
        return false;
    }
{code}

Notice that we are given the {{Consumer}} as a parameter. We could use this to _restart_ the consumer as we can invoke stop and start:
{code}
    // error occurred lets restart the consumer, that could maybe resolve the issue
    consumer.stop();
    consumer.start();
{code}

*Notice:* If you implement the {{begin}} operation make sure to avoid throwing exceptions as in such a case the {{poll}} operation is not invoked and Camel will invoke the {{rollback}} directly.

h4. Configuring an [Endpoint] to use {{PollingConsumerPollStrategy}}
To configure an [Endpoint] to use a custom {{PollingConsumerPollStrategy}} you use the option {{pollStrategy}}. For example in the file consumer below we want to use our custom strategy defined in the [Registry] with the bean id {{myPoll}}:
{code}
    from("file://inbox/?pollStrategy=#myPoll").to("activemq:queue:inbox")
{code}

{include:Using This Pattern}

h3. See Also
- [POJO Consuming]
- [Batch Consumer]