Search code examples
javaspringapache-cameldslspring-camel

Implement counter variable in camel route


I am trying to get the List of employee details From Database and Push it in to External System using REST API. I am able to create a route for the above flow .

Also, I want to know the count of created and failure records. So i created a counter by setting property with value 0 and then increment the property value . When i try to increment the property value it always the same as what i initialized.

 from("direct:test")
    .setBody(constant("select name as name, location as location,mobile as mobile from employee"))
    .to("jdbc:testdb")
    .process(exchange ->{
        // Custom Logic which will convert list of Employee  Details
    })
    .split(body())
    .setProperty("successrec", simple("0"))
    .setProperty("failurerec", simple("0"))
    .doTry()
    .setProperty("successrec", simple("${property.successrec++}"))
    .to("http://test/upload/employee")
    .doCatch((Exception.class)).process( exchange ->{   
        
        Integer failureRecords=exchange.getProperty("failurerec",Integer.class);
        exchange.setProperty("failurerec", failureRecords++);

     });

I tried even using processor to set and get the property value, But it didn't worked . Is there any way i can have a counter over success and failure records.


Solution

  • Properties are local to an exchange so you may need to use a Route Policy to inject a global counter.

    Create a route policy:

    class MyRoutePolicy extends RoutePolicySupport {
        private AtomicInteger counter = new AtomicInteger();
    
        @Override
        public void onExchangeBegin(Route route, Exchange exchange) {
            exchange.setProperty("counter", counter);
        }
    
        public int getCounter() {
            return counter.get();
        }
    };
    

    Associate the policy to the route:

    MyRoutePolicy policy = new MyRoutePolicy();
    
    from("direct:test")
        .routePolicy(policy)
        ...
    

    This is one of the possible solutions but you may also using a global counter that depending on your needs, may be simpler.