Camel Components

JCache

Since Camel 2.17

Both producer and consumer are supported

The JCache component enables you to perform caching operations using JSR107/JCache as cache implementation.

URI Format

jcache:cacheName[?options]

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The JCache component supports the following options which are listed below.

Name Description Default Type

cacheConfiguration (common)

The default JCache Configuration of the endpoints, to create a cache with when it does not exist yet. When set, the cache options of the endpoint (such as readThrough and expiryPolicyFactory) are not used.

Configuration

cacheConfigurationProperties (common)

The default provider specific properties of the endpoints, which the CachingProvider gets when it creates the CacheManager. The provider creates one CacheManager per configurationUri and reuses it, so only the properties of the first use count. Takes precedence over cacheConfigurationPropertiesRef.

Map

cacheConfigurationPropertiesRef (common)

The name of a Map or Properties bean in the registry to use as cacheConfigurationProperties, when that option is not set.

String

cachingProvider (common)

The default JCache CachingProvider of the endpoints: the fully qualified class name of a javax.cache.spi.CachingProvider, or one of the short names hazelcast, ehcache, caffeine and infinispan-embedded. When not set, the provider named by the javax.cache.spi.CachingProvider system property is used, or else the only CachingProvider on the classpath (it fails when there is none or more than one).

String

configurationUri (common)

The default implementation specific URI of the CacheManager of the endpoints, such as the location of a configuration file of the provider. Property placeholders are resolved. When not set, the default URI of the provider is used.

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

Endpoint Options

The JCache endpoint is configured using URI syntax:

jcache:cacheName

With the following path and query parameters:

Path Parameters

Name Description Default Type

cacheName (common)

Required The name of the cache.

String

Query Parameters

Name Description Default Type

cacheConfigurationProperties (common)

The provider specific Properties that the CachingProvider gets when it creates the CacheManager. The provider creates one CacheManager per configurationUri and reuses it, so only the properties of the first use count.

Properties

cachingProvider (common)

The JCache CachingProvider to use: the fully qualified class name of a javax.cache.spi.CachingProvider, or one of the short names hazelcast, ehcache, caffeine and infinispan-embedded. When not set, the provider named by the javax.cache.spi.CachingProvider system property is used, or else the only CachingProvider on the classpath (it fails when there is none or more than one).

String

configurationUri (common)

The implementation specific URI of the CacheManager to get from the CachingProvider, such as the location of a configuration file of the provider. Property placeholders are resolved. When not set, the default URI of the provider is used.

String

managementEnabled (common)

Whether management is enabled for the cache, which registers its CacheMXBean in JMX (javax.cache:type=CacheConfiguration). Applies only when the endpoint creates the cache (see createCacheIfNotExists) and cacheConfiguration is not set.

false

boolean

readThrough (common)

Whether the cache is in read-through mode: a get of a key that is not in the cache loads its value with the CacheLoader of cacheLoaderFactory. Applies only when the endpoint creates the cache (see createCacheIfNotExists) and cacheConfiguration is not set.

false

boolean

statisticsEnabled (common)

Whether the cache collects statistics, which the provider exposes as a CacheStatisticsMXBean in JMX (javax.cache:type=CacheStatistics). Applies only when the endpoint creates the cache (see createCacheIfNotExists) and cacheConfiguration is not set.

false

boolean

storeByValue (common)

Whether the cache stores a copy of each key and value (store-by-value, usually serialized) instead of a reference to the objects (store-by-reference). Store-by-reference is an optional JCache feature that not every provider supports. Applies only when the endpoint creates the cache (see createCacheIfNotExists) and cacheConfiguration is not set.

true

boolean

writeThrough (common)

Whether the cache is in write-through mode: a put or removal of an entry also calls the CacheWriter of cacheWriterFactory. Applies only when the endpoint creates the cache (see createCacheIfNotExists) and cacheConfiguration is not set.

false

boolean

filteredEvents (consumer)

The cache entry event types that the consumer does not receive, separated by commas. Not used when eventFilters is set.

Enum values:

  • CREATED

  • UPDATED

  • REMOVED

  • EXPIRED

String

oldValueRequired (consumer)

Whether the cache entry listener of the consumer requires the old value: the provider then gives the previous value of the entry with UPDATED, REMOVED and EXPIRED events, and the consumer puts it in the CamelJCacheOldValue header. When false, the provider may still give it.

false

boolean

synchronous (consumer)

Whether the cache entry listener of the consumer is synchronous: the cache operation that caused an event does not return until the consumer has routed the event. When false, the provider delivers the events asynchronously.

false

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

eventFilters (consumer (advanced))

The CacheEntryEventFilter instances that decide which cache entry events the consumer receives: an event is received only when every filter accepts it. Given as references to beans in the registry, separated by commas (such as #myFilter), or a bean that is a List of filters. Takes precedence over filteredEvents.

List

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

action (producer)

The default cache operation of the producer: PUT, PUTALL, PUTIFABSENT, GET, GETALL, GETANDREMOVE, GETANDREPLACE, GETANDPUT, REPLACE, REMOVE, REMOVEALL, INVOKE or CLEAR (case insensitive). The CamelJCacheAction header takes precedence. A message fails when neither sets an operation.

String

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

cacheConfiguration (advanced)

The JCache Configuration to create the cache with, when it does not exist yet (see createCacheIfNotExists). When set, the options cacheLoaderFactory, cacheWriterFactory, expiryPolicyFactory, readThrough, writeThrough, storeByValue, statisticsEnabled and managementEnabled are not used.

Configuration

cacheLoaderFactory (advanced)

The Factory of the CacheLoader that loads an entry that is not in the cache, in read-through mode (see readThrough). Applies only when the endpoint creates the cache (see createCacheIfNotExists) and cacheConfiguration is not set.

Factory

cacheWriterFactory (advanced)

The Factory of the CacheWriter that the cache passes its puts and removals to, in write-through mode (see writeThrough). Applies only when the endpoint creates the cache (see createCacheIfNotExists) and cacheConfiguration is not set.

Factory

createCacheIfNotExists (advanced)

Whether to create the cache when the CacheManager has no cache of this name (and cannot create it from the configuration of the provider): with cacheConfiguration when set, else with the cache options of the endpoint. When false and the cache does not exist, the producer or consumer fails to start.

true

boolean

expiryPolicyFactory (advanced)

The Factory of the ExpiryPolicy that decides when the entries of the cache expire. When not set, the entries never expire (EternalExpiryPolicy). Applies only when the endpoint creates the cache (see createCacheIfNotExists) and cacheConfiguration is not set.

Factory

lookupProviders (advanced)

Not used: the component does not read this option, so it has no effect. The caching provider is chosen by cachingProvider.

false

boolean

Message Headers

The JCache component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelJCacheAction (producer)

Constant: ACTION

The cache operation to perform, such as PUT or GET (case insensitive). Takes precedence over the action option.

String

CamelJCacheResult (producer)

Constant: RESULT

Whether the PUTIFABSENT, REPLACE or REMOVE operation changed the cache.

boolean

CamelJCacheEventType (consumer)

Constant: EVENT_TYPE

The type of the cache entry event: CREATED, UPDATED, REMOVED or EXPIRED.

String

CamelJCacheKey (common)

Constant: KEY

The key of the cache entry: for the producer, the entry to operate on; for the consumer, the entry of the event.

Object

CamelJCacheKeys (producer)

Constant: KEYS

The set of keys of the GETALL, REMOVEALL and INVOKE operations. REMOVEALL without it removes all the entries, and INVOKE with it invokes the EntryProcessor on these keys instead of the CamelJCacheKey header.

Set

CamelJCacheOldValue (consumer)

Constant: OLD_VALUE

For the consumer, the previous value of the entry of an UPDATED, REMOVED or EXPIRED event, when the provider gives it (see oldValueRequired). For the producer, the value that the entry must have for REPLACE and REMOVE to change it.

Object

CamelJCacheEntryProcessor (producer)

Constant: ENTRY_PROCESSOR

The EntryProcessor that the INVOKE operation invokes on the entry of the CamelJCacheKey header, or on the entries of the CamelJCacheKeys header.

EntryProcessor

CamelJCacheEntryArgs (producer)

Constant: ARGUMENTS

The arguments for the EntryProcessor of the INVOKE operation, as a Collection. The EntryProcessor gets the Collection itself as its only argument, not its elements.

Collection

Message Body

The message body at each side of the JCache component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

unknown

The value of the entry, as it was put, with the key in the CamelJCacheKey header and the event (CREATED, UPDATED, REMOVED or EXPIRED) in CamelJCacheEventType; with oldValueRequired the previous value is in the CamelJCacheOldValue header. A REMOVED or EXPIRED event has the old value as body when the provider gives it (Hazelcast does with oldValueRequired), else no body.

Producer input

any

The value to store for PUT, PUTIFABSENT, REPLACE, GETANDPUT and GETANDREPLACE, as it is, and a Map of the entries for PUTALL; no body, or a body that is not a Map for PUTALL, fails. A provider that stores by value serializes it: a stream fails, so convert it to text or bytes first. The other actions do not use the body.

Producer output

unknown

By the action, which the CamelJCacheAction header can set: the value of the key for GET, or no body when it is not in the cache; the previous value, or no body, for GETANDPUT, GETANDREPLACE and GETANDREMOVE; a Map of the keys found to their values for GETALL; the result of the EntryProcessor for INVOKE, a Map of the keys to their EntryProcessorResult with CamelJCacheKeys. The other actions keep the body; PUTIFABSENT, REPLACE and REMOVE put whether they changed the cache in the CamelJCacheResult header.

  • With action=GETALL: map (java.util.Map)

  • With action=PUT: unchanged

  • With action=PUTALL: unchanged

  • With action=PUTIFABSENT: unchanged

  • With action=REPLACE: unchanged

  • With action=REMOVE: unchanged

  • With action=REMOVEALL: unchanged

  • With action=CLEAR: unchanged

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

Producer operations

The producer performs one cache operation per message: the action option sets the default, and the CamelJCacheAction header overrides it per message. The operations are PUT, PUTALL, PUTIFABSENT, GET, GETALL, GETANDREMOVE, GETANDREPLACE, GETANDPUT, REPLACE, REMOVE, REMOVEALL, CLEAR and INVOKE. The CamelJCacheKey header names the entry (CamelJCacheKeys, a set of keys, for the ALL operations), the message body is the value to store, and a GET puts the value found in the body. PUTALL takes no key header: the body is a Map of the keys and the values to store, and any other body fails with an InvalidPayloadException.

Storing a value under a key:

  • Java

  • XML

  • YAML

from("direct:put")
    .setHeader(JCacheConstants.KEY, constant("123"))
    .to("jcache:orders?action=PUT");
<route>
    <from uri="direct:put"/>
    <setHeader name="CamelJCacheKey">
        <constant>123</constant>
    </setHeader>
    <to uri="jcache:orders?action=PUT"/>
</route>
- route:
    from:
      uri: direct:put
      steps:
        - setHeader:
            name: CamelJCacheKey
            expression:
              constant:
                expression: "123"
        - to:
            uri: jcache:orders?action=PUT

Reading a value back, the operation chosen by the header:

  • Java

  • XML

  • YAML

from("direct:get")
    .setHeader(JCacheConstants.ACTION, constant("GET"))
    .setHeader(JCacheConstants.KEY, constant("123"))
    .to("jcache:orders")
    .log("Order 123 is ${body}");
<route>
    <from uri="direct:get"/>
    <setHeader name="CamelJCacheAction">
        <constant>GET</constant>
    </setHeader>
    <setHeader name="CamelJCacheKey">
        <constant>123</constant>
    </setHeader>
    <to uri="jcache:orders"/>
    <log message="Order 123 is ${body}"/>
</route>
- route:
    from:
      uri: direct:get
      steps:
        - setHeader:
            name: CamelJCacheAction
            expression:
              constant:
                expression: GET
        - setHeader:
            name: CamelJCacheKey
            expression:
              constant:
                expression: "123"
        - to:
            uri: jcache:orders
        - log:
            message: "Order 123 is ${body}"

Consuming cache events

The consumer receives the events of the cache: the CamelJCacheEventType header is CREATED, UPDATED, REMOVED or EXPIRED, CamelJCacheKey is the key, the body is the value, and with oldValueRequired=true the CamelJCacheOldValue header is the previous value. The filteredEvents option names the events to leave out:

  • Java

  • XML

  • YAML

from("jcache:orders?filteredEvents=EXPIRED")
    .log("Order ${header.CamelJCacheKey} was ${header.CamelJCacheEventType}: ${body}");
<route>
    <from uri="jcache:orders?filteredEvents=EXPIRED"/>
    <log message="Order ${header.CamelJCacheKey} was ${header.CamelJCacheEventType}: ${body}"/>
</route>
- route:
    from:
      uri: jcache:orders?filteredEvents=EXPIRED
      steps:
        - log:
            message: "Order ${header.CamelJCacheKey} was ${header.CamelJCacheEventType}: ${body}"

JCache Policy

The JCachePolicy is an interceptor around a route that caches the "result of the route" (the message body) after the route is completed. If the next time the route is called with a "similar" Exchange, the cached value is used on the Exchange instead of executing the route. The policy uses the JSR107/JCache API of a cache implementation, so it’s required to add one (e.g., Hazelcast, Ehcache) to the classpath.

The policy takes a key value from the received Exchange to get or store values in the cache. By default, the key is the message body. For example, if the route - having a JCachePolicy - receives an Exchange with a String body "fruit" and the body at the end of the route is "apple", it stores a key/value pair "fruit=apple" in the cache. If next time another Exchange arrives with a body "fruit", the value "apple" is taken from the cache instead of letting the route process the Exchange.

So by default, the message body at the beginning of the route is the cache key and the body at the end is the stored value. It’s possible to use something else as a key by setting a Camel Expression via .setKeyExpression() that will be used to determine the key.

The policy needs a JCache Cache. It can be set directly by .setCache() or the policy will try to get or create the Cache based on the other parameters set.

Similar caching solution is available, for example, in Spring using the @Cacheable annotation.

JCachePolicy Fields

Name Description Default Type

cache

The Cache to use to store the cached values. If this value is set, cacheManager, cacheName and cacheConfiguration is ignored.

Cache

cacheManager

The CacheManager to use to look up or create the Cache. Used only if cache is not set.

Try to find a CacheManager in the CamelContext registry or calls the standard JCache Caching.getCachingProvider().getCacheManager().

CacheManager

cacheName

Name of the cache. Get the Cache from cacheManager or create a new one if it doesn’t exist.

RouteId of the route.

String

cacheConfiguration

JCache cache configuration to use if a new Cache is created

Default new MutableConfiguration object.

CacheConfiguration

keyExpression

An Expression to evaluate to determine the cache key.

Exchange body

Expression

enabled

If the policy is not enabled, no wrapper processor is added to the route. It has impact only during startup, not during runtime. For example, it can be used to disable caching from properties.

true

boolean

How to determine cache to use?

Set cache

The cache used by the policy can be set directly. This means you have to configure the cache yourself and get a JCache Cache object, but this gives the most flexibility. For example, it can be setup in the config xml of the cache provider (Hazelcast, EhCache, …​) and used here. Or it’s possible to use the standard Caching API as below:

Java-only: Java programmatic cache configuration with JCachePolicy
MutableConfiguration configuration = new MutableConfiguration<>();
configuration.setTypes(String.class, Object.class);
configuration.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 60)));
CacheManager cacheManager = Caching.getCachingProvider().getCacheManager();
Cache cache = cacheManager.createCache("orders",configuration);

JCachePolicy jcachePolicy = new JCachePolicy();
jcachePolicy.setCache(cache);

from("direct:get-orders")
    .policy(jcachePolicy)
    .log("Getting order with id: ${body}")
    .bean(OrderService.class,"findOrderById(${body})");

Set cacheManager

If the cache is not set, the policy will try to look up or create the cache automatically. If the cacheManager is set on the policy, it will try to get cache with the set cacheName (routeId by default) from the CacheManager. If the cache does not exist, it will create a new one using the cacheConfiguration (new MutableConfiguration by default).

Java-only: Java programmatic CacheManager configuration
//In a Spring environment, for example, the CacheManager may already exist as a bean
@Autowire
CacheManager cacheManager;
...

//Cache "items" is used or created if not exists
JCachePolicy jcachePolicy = new JCachePolicy();
jcachePolicy.setCacheManager(cacheManager);
jcachePolicy.setCacheName("items")

Find cacheManager

If cacheManager (and the cache) is not set, the policy will try to find a JCache CacheManager object:

  • Lookup a CacheManager in Camel registry. That falls back on JNDI or Spring context based on the environment

  • Use the standard api Caching.getCachingProvider().getCacheManager()

Java-only: Java DSL with JCachePolicy
//A Cache "getorders" will be used (or created) from the found CacheManager
from("direct:get-orders").routeId("getorders")
    .policy(new JCachePolicy())
    .log("Getting order with id: ${body}")
    .bean(OrderService.class,"findOrderById(${body})");

Partially wrapped route

In the examples above, the whole route was executed or skipped. A policy can be used to wrap only a segment of the route instead of all processors.

Java-only: Java DSL with partial JCachePolicy wrapping
from("direct:get-orders")
    .log("Order requested: ${body}")
    .policy(new JCachePolicy())
        .log("Getting order with id: ${body}")
        .bean(OrderService.class,"findOrderById(${body})")
    .end()
    .log("Order found: ${body}");

The .log() at the beginning and at the end of the route is always called, but the section inside .policy() and .end() is executed based on the cache.

KeyExpression

By default, the policy uses the received Exchange body as the key, so the default expression is like simple("${body}"). We can set a different Camel Expression as keyExpression which will be evaluated to determine the key. For example, if we try to find an order by an orderId which is in the message headers, set header("orderId") (or simple("$\{header.orderId\}") as keyExpression.

The expression is evaluated only once at the beginning of the route to determine the key. If nothing was found in cache, this key is used to store the value in cache at the end of the route.

Java-only: Java programmatic JCachePolicy with keyExpression
MutableConfiguration configuration = new MutableConfiguration<>();
configuration.setTypes(String.class, Order.class);
configuration.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 10)));

JCachePolicy jcachePolicy = new JCachePolicy();
jcachePolicy.setCacheConfiguration(configuration);
jcachePolicy.setCacheName("orders")
jcachePolicy.setKeyExpression(simple("${header.orderId}))

//The cache key is taken from "orderId" header.
from("direct:get-orders")
    .policy(jcachePolicy)
    .log("Getting order with id: ${header.orderId}")
    .bean(OrderService.class,"findOrderById(${header.orderId})");

BypassExpression

The JCachePolicy can be configured with an Expression that can per Exchange determine whether to look up the value from the cache or bypass. If the expression is evaluated to false then the route is executed as normal, and the returned value is inserted into the cache for future lookup.

Camel XML DSL examples

Use JCachePolicy in an XML route

In Camel XML DSL, we need a named reference to the JCachePolicy instance (registered in CamelContext or simply in Spring). We have to wrap the route between <policy>…​</policy> tags after <from>.

  • Java

  • XML

  • YAML

from("direct:get-order")
    .policy("jCachePolicy")
        .setBody().method("orderService", "findOrderById(${body})")
    .end();
<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:get-order"/>
        <policy ref="jCachePolicy" >
            <setBody>
                <method ref="orderService" method="findOrderById(${body})"/>
            </setBody>
        </policy>
    </route>
</camelContext>
- route:
    from:
      uri: direct:get-order
      steps:
        - policy:
            ref: jCachePolicy
            steps:
              - setBody:
                  method:
                    ref: orderService
                    method: "findOrderById(${body})"

See this example when only a part of the route is wrapped:

  • Java

  • XML

  • YAML

from("direct:get-order")
    .log("Start - This is always called. body:${body}")
    .policy("jCachePolicy")
        .log("Executing route, not found in cache. body:${body}")
        .setBody().method("orderService", "findOrderById(${body})")
    .end()
    .log("End - This is always called. body:${body}");
<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:get-order"/>
        <log message="Start - This is always called. body:${body}"/>
        <policy ref="jCachePolicy" >
            <log message="Executing route, not found in cache. body:${body}"/>
            <setBody>
                <method ref="orderService" method="findOrderById(${body})"/>
            </setBody>
        </policy>
        <log message="End - This is always called. body:${body}"/>
    </route>
</camelContext>
- route:
    from:
      uri: direct:get-order
      steps:
        - log:
            message: "Start - This is always called. body:${body}"
        - policy:
            ref: jCachePolicy
            steps:
              - log:
                  message: "Executing route, not found in cache. body:${body}"
              - setBody:
                  method:
                    ref: orderService
                    method: "findOrderById(${body})"
        - log:
            message: "End - This is always called. body:${body}"

Define CachePolicy in Spring

It’s more convenient to create a JCachePolicy in Java, especially within a RouteBuilder using the Camel DSL expressions, but see this example to define it in a Spring XML:

<bean id="jCachePolicy" class="org.apache.camel.component.jcache.policy.JCachePolicy">
    <property name="cacheName" value="spring"/>
    <property name="keyExpression">
        <bean class="org.apache.camel.model.language.SimpleExpression">
            <property name="expression" value="${header.mykey}"/>
        </bean>
    </property>
</bean>

Create Cache from XML

It’s not strictly speaking related to Camel XML DSL, but JCache providers usually have a way to configure the cache in an XML file. For example with Hazelcast, you can add a hazelcast.xml to classpath to configure the cache "spring" used in the example above.

<hazelcast xmlns="http://www.hazelcast.com/schema/config"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.hazelcast.com/schema/config http://www.hazelcast.com/schema/config/hazelcast-config-4.0.xsd">

    <cache name="spring">
        <key-type class-name="java.lang.String"/>
        <value-type class-name="java.lang.String"/>
        <expiry-policy-factory>
            <timed-expiry-policy-factory expiry-policy-type="CREATED" duration-amount="60" time-unit="MINUTES"/>
        </expiry-policy-factory>
    </cache>

</hazelcast>

Special scenarios and error handling

If the Cache used by the policy is closed (can be done dynamically), the whole caching functionality is skipped, the route will be executed every time.

If the determined key is null, nothing is looked up or stored in cache.

In case of an exception during the route, the error handled is called as always. If the exception gets handled(), the policy stores the Exchange body. Otherwise, nothing is added to the cache. If an exception happens during evaluating the keyExpression, the routing fails, the error handler is called as normally.