Camel Error Handling With Redelivery Example

Error Handling With Redelivery Example In Camel with simple steps.


In our example we will learn how can camel handle error.How policy can be defined for error during handling.As a broker we are using ActiveMQ.So we have assumed you have ActiveMQ in your local machine.

camel provides many error handler for example

  • DefaultErrorHandler
  • NoErrorHandler
  • DeadLetterChannel
  • LoggingErrorHandler
  • TransactionErrorHandler

Among above DefaultErrorHandler is default.In this tutorial we are going to learn DeadLetterChannel.

  • In eclipse create a maven project MyFirstCamelErrorHandler as we created in earlier page and right click on src/main/java to create package. New -> package



  • Give any name for example com.preparationforinterview.errorhandler.javadsl and click on Finish



  • Right click on package and create a java class for example Executor.



  • Right click on package and create one more java class for example ErrorHandlerRoute.



  • Right click on package and create a java class for example MyProcessor.



  • Add following dependency in pom.xml file.you can use any latest version.

  •  	
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-core</artifactId>
    			<version>2.13.0</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-jms</artifactId>
    			<version>2.5.0</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.activemq</groupId>
    			<artifactId>activemq-core</artifactId>
    			<version>5.3.2</version>
    		</dependency>
    
  • Run mvn:install from command prompt or if you are using Eclipse right click on pom.xml and run mvn install.It will download camel jars

  • Copy below code in MyProcessor.

  •  		
    package com.preparationforinterview.errorhandler.javadsl;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    
    public class MyProcessor implements Processor{
    
    	public void process(Exchange exchange) throws Exception {
    		System.out.println("processing " + exchange.getIn().getBody(String.class));
    		exchange.getIn().setBody("Hello Good Morning");
    		throw new Exception();
    		
    	}
    
    }
    
    
    

    Explain

    We created processor and printing incoming message and at the same time we are changing out going message so that we can show that during error handling what happens to outgoing message and sending an exception so that our error handler can trigger.

  • Copy below code in ErrorHandlerRoute.

  •  		
    package com.preparationforinterview.errorhandler.javadsl;
    
    import org.apache.camel.builder.RouteBuilder;
    
    public class ErrorHandlerRoute extends RouteBuilder {
    
    	@Override
    	public void configure() throws Exception {
    		errorHandler(deadLetterChannel("jms:queue:dlq").maximumRedeliveries(2)
    				.redeliveryDelay(1000).useOriginalMessage());
    
    		from("jms:queue:input").process(new MyProcessor()).to(
    				"jms:queue:preparationforinterview");
    	}
    }
    
    

    Explain

    To create a route in camel we need to extend RouteBuilder class and override configure method.In configure method we define our route.In above example we can read it as from input queue take message and call our processor which will throw exception.We will not getting any message to our output queue preparationforinterview.Here jms: is called endpoint.

    In error handler we have mentioned our policy that if any exception occurs then attempt 2 time more with 1 second interval,if after that still exception occurs then send message to dlq.

  • Copy below code in Executor.

  •  	
    package com.preparationforinterview.errorhandler.javadsl;
    
    import javax.jms.ConnectionFactory;
    
    import org.apache.activemq.ActiveMQConnectionFactory;
    import org.apache.camel.CamelContext;
    import org.apache.camel.component.jms.JmsComponent;
    import org.apache.camel.impl.DefaultCamelContext;
    
    public class Executor {
    
    	public static void main(String args[]) throws Exception {
    		CamelContext context = new DefaultCamelContext();
    		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
    		context.addComponent("jms",
    				JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
    		context.addRoutes(new ErrorHandlerRoute());
    		context.start();
    		Thread.sleep(100000);
    		context.stop();
    	}
    
    }
    

    Explain

    First we need to create CamelContext. It has many implementation but we are using DefaultCamelContext.Camel provides ConnectionFactory but to which provider we need to connect we have to give that here we are using ActiveMQ so give ActiveMQConnectionFactory and add it to camel JmsComponent and link it to "jms" name ,you can use any name but whatever you will give, use same in ErrorHandlerRoute router class.After that add route in camel context.Its like registry of route in CamelContext, till that part we have just configured route in CamelContext but until and unless we start CamelContext it will not execute route.We kept Thread.sleep(1000) so that camel gets enough time to copy file from input to output folder.

    To check the output right click on Executor.java and run it.It will show as below.


    Send a message say Hello World


    When we send message to input queue, route will pick message and will call out processor ,processor changing this message to Hello Good Morning.As per policy on when exception will be thrown it will retry it with two attempts so on console we get three processing message ,one for actual and 2 for retry.


    After two retry camel exhausts and send message to dlq.


    It sends changed message to dlq but if we wants to send original message after camel exhausts after retry then use

     	
    		errorHandler(deadLetterChannel("jms:queue:dlq").maximumRedeliveries(2)
    				.redeliveryDelay(1000).useOriginalMessage());
    	

    Similarly if we want to do by spring

     	
    	<errorHandler id="myErrorHandler" type="DeadLetterChannel"
    	deadLetterUri="jms:queue:dead" useOriginalMessage="true"/>
    	<redeliveryPolicy maximumRedeliveries="5"
    	retryAttemptedLogLevel="WARN"
    	backOffMultiplier="2"
    	useExponentialBackOff="true"/>
    	</errorHandler>
    
    	
    To run the program from command prompt, open command prompt and go to project location and run below command.
    mvn compile exec:java -Dexec.mainClass=com.preparationforinterview.errorhandler.javadsl.Executor

    Note :

    Camel provide two scope for error handler
    • Context: All route will use same error handle
    • Route:Only that route where it is defined will use that error handler
  • To define error handler at route level
  • Copy below code in ErrorHandlerRoute.

  •  		
    	package com.preparationforinterview.errorhandler.javadsl;
    	
    	import org.apache.camel.builder.RouteBuilder;
    	
    	public class ErrorHandlerRoute extends RouteBuilder {
    	
    		@Override
    		public void configure() throws Exception {
    	
    			from("jms:queue:input").errorHandler(deadLetterChannel("jms:queue:dlq").maximumRedeliveries(2)
    					.redeliveryDelay(1000).useOriginalMessage()).process(new MyProcessor()).to(
    					"jms:queue:preparationforinterview");
    		}
    	}
    

Download source code

Camel Error Handling With Redelivery Example Using Java DSL


Visit Others Links

Camel Introduction
Camel Setup
File Copy Example Using Camel
File Copy Example In Camel Using Spring
JMS Message Transfer Example Using Camel
JMS Message Transfer Example In Camel Using Spring
Processor In Camel
Object to JSON Transfer Example Using Spring In Camel
Camel With Bean Injection Example Using Spring DSL
Camel With Bean Injection Registry Example Using Java DSL
Camel Bean Parameter Binding Example Using Java DSL
Camel Error Handling With Redelivery Example Using Java DSL
Camel Exception Handling With Example Using Java DSL
Camel JUnit Test With Example Using Java DSL
Camel JUnit Test With Example Using Spring DSL
Camel Unit Test With Mock Component Example
Camel With Stream Component Example
Camel In-Memory Messaging Example Using Direct
Camel With Timer And Quartz Example
Camel Aggregator EIP Example
Camel Splitter EIP Example
Camel Routing Slip EIP Example
Camel Dynamic Router EIP Example
Camel Load Balancer EIP Example
Top Camel Interview Question
© 2019 PreparationForInterview.com