Search code examples
apache-camelcircuit-breaker

How to combine retry and circuit breaker in Apache Camel?


I would like to retry for say 3 times, and then increase failure threshold to 1. When this threshold reaches 5, I would like to open the circuit in Apache Camel.

I understand there is circuit breaker support in Camel, however I couldn't find an example where retry can be combined with it.

Any help is greatly appreciated.

Thanks in advance.

Ramesh.


Solution

  • Can you try the below code

    <!--  Just Throws an exception of type MyException which is a custom Exception -->
    <bean id="myBean" class="com.camel.examples.MyExceptionClass" />
    <camel:errorHandler id="defaultErrorHandler" type="DefaultErrorHandler">
        <camel:redeliveryPolicy maximumRedeliveries="3"
            redeliveryDelay="1000" logStackTrace="false" />
    </camel:errorHandler>
    <camel:camelContext>
        <camel:route>
            <camel:from uri="timer:foo?repeatCount=8&amp;period=10000" />
            <camel:setBody>
                <camel:constant>Sundar</camel:constant>
            </camel:setBody>
            <camel:loadBalance>
                <camel:circuitBreaker threshold="5" halfOpenAfter="1000">
                    <camel:exception>java.lang.Exception</camel:exception>
                </camel:circuitBreaker>
                <camel:to uri="direct:a" />
            </camel:loadBalance>
        </camel:route>
        <camel:route id="myroute" errorHandlerRef="defaultErrorHandler">
            <camel:from uri="direct:a" />
            <camel:process ref="myBean"></camel:process>
            <camel:log message="${exception}]" />
        </camel:route>
    </camel:camelContext>
    

    Class MyExceptionClass.java

    package com.camel.examples;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class MyExceptionClass implements Processor{
        Logger Logger = LoggerFactory.getLogger(MyExceptionClass.class);
        @Override
        public void process(Exchange exchange) throws Exception {   
            throw new MyException("Other Exceptions");
        }
    }
    

    MyException Class

    package com.camel.examples;
    
    public class MyException extends Exception{
    
        public MyException() {
        super();
    
        }
    
        public MyException(String message){
            super("My Exception : "+message);
        }
    }