[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Policy to wrap route with a cache

Hi Camel Users,

In Spring we have the @Cacheable
annotation that provides an easy way to wrap a method call with a cache.
The method result is cached and the method is not executed the next time
the it's called with the same input parameters.

I was wondering if we have something similar for Camel routes, where we can
cache the "result" of a route and execute the next time only if nothing is
found in the cache.

I haven't found any solution out-of-the-box, but a few blogs
about doing similar caching in certain specific scenarios using the Policy
for processors. So I tried to put together a more generic solution:
See CachePolicy class:

This is how it can be used in a route:

public class CachedRoute extends RouteBuilder{
    public void configure() throws Exception {


    //Cache user data by user name. If user data is found in cache the rest
of the route is not executed.
    *private Policy getUserDataCachePolicy()*{
        CachePolicy cachePolicy = new CachePolicy();

        //User name is the cache key

        //What to do with the cached object if found
        cachePolicy.setApplyCachedObject(new BiConsumer<Exchange, Object>()
            public void accept(Exchange exchange, Object cached){

        //Cache userData at the end of the route

        return cachePolicy;

It would be great to know if someone tried anything similar and especially
if the "AsyncCallback()" looks OK in CachePolicy.wrap(). I found that piece
always a bit tricky...