Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I share local data between Camel Routes in the same Camel context?

Tags:

apache-camel

I have a route (route1), which sends data to an HTTP endpoint. To do this, it must set an authorization header. The header value times out every hour and must be renewed.

For this I have created another route (route2), which gets the access token from a web service at a regular interval using provided credentials (getCredentials). This works fine.

How do I make the access token available to route1?

I have tried simple local variables, static variables, AtomicReference variables (volatile and static...)

My code (shortened for readability):

public class DataRoute extends RouteBuilder{

    volatile static AtomicReference<String> cache = new AtomicReference<>();

    @Override
    public void configure() throws Exception {

        from("timer://test?period=3500000")
                .routeId("route2")
                .setHeader("Authorization", constant(getCredentials()))
                .to("http://127.0.0.1:8099/v1/login")
                .process(exchange -> {
                    cache.set(parseAuthString(exchange.getIn().getBody(String.class)));
                });


        ... other route producing for direct:rest       

        from("direct:rest")
                .routeId("route1")
                .setHeader("Authorization",constant((cache.get()==null?"":cache.get())))
                .to("http://localhost:8099/v1/shipment");

    }
}

The cached value is always empty...

like image 772
MartinW Avatar asked Sep 12 '25 03:09

MartinW


1 Answers

Do not use constant to set dynamic values, its a one-time CONSTANT only.

Instead use an inlined processor (you can use java 8 lambda) or message transform / setBody with a processor.

like image 63
Claus Ibsen Avatar answered Sep 14 '25 02:09

Claus Ibsen