Camel Components

Caffeine LoadCache

Since Camel 2.20

Only producer is supported

The Caffeine LoadCache component enables you to perform caching operations using the LoadingCache from Caffeine.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-caffeine</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

caffeine-loadcache://cacheName[?options]

You can append query options to the URI in the following format: ?option=value&option=#beanRef&…​

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 Caffeine LoadCache component supports the following options which are listed below.

Name Description Default Type

action (producer)

The action to perform when the message has no CamelCaffeineAction header. When neither sets an action, the exchange fails.

Enum values:

  • GET

  • GET_ALL

  • PUT

  • PUT_ALL

  • INVALIDATE

  • INVALIDATE_ALL

  • CLEANUP

  • AS_MAP

String

createCacheIfNotExist (producer)

Whether the component creates the cache when the registry has no cache bean with the cache name. The component keeps the caches it creates by name, so the endpoints with the same cache name share one cache, which the options of the first of these endpoints to start configure. The cache options (evictionType, maximumSize and the others) only apply to a cache that the component creates. When false and the registry has no such bean, the endpoint fails to start.

true

boolean

evictionType (producer)

Which options configure the eviction of the cache: SIZE_BASED uses initialCapacity and maximumSize, and TIME_BASED uses expireAfterAccessTime and expireAfterWriteTime. The options of the other type are ignored.

Enum values:

  • SIZE_BASED

  • TIME_BASED

SIZE_BASED

EvictionType

expireAfterAccessTime (producer)

The time in seconds after the last read or write of an entry, or its creation, after which Caffeine removes the entry from the cache (Caffeine expireAfterAccess). With 0, entries expire right away. Only used when evictionType is TIME_BASED, together with expireAfterWriteTime: an entry expires at the first of the two times.

300

int

expireAfterWriteTime (producer)

The time in seconds after the creation of an entry, or the last replacement of its value, after which Caffeine removes the entry from the cache (Caffeine expireAfterWrite). With 0, entries expire right away. Only used when evictionType is TIME_BASED, together with expireAfterAccessTime: an entry expires at the first of the two times.

300

int

initialCapacity (producer)

The minimum total size of the internal data structures of the cache (Caffeine initialCapacity). A large enough estimate avoids resizing later, but a too large value wastes memory. Only used when evictionType is SIZE_BASED; when not set, Caffeine uses its default.

Integer

key (producer)

The key of the entry for the GET, PUT and INVALIDATE actions when the message has no CamelCaffeineKey header. When neither sets a key, these actions fail.

String

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

maximumSize (producer)

The maximum number of entries the cache may contain (Caffeine maximumSize). As the size grows close to the maximum, Caffeine evicts the entries that are less likely to be used again, and it may evict an entry before the limit is exceeded or exceed it for a short time while evicting. With 0, Caffeine evicts each entry right after it is stored. Only used when evictionType is SIZE_BASED; when not set, the size of the cache has no limit.

Integer

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

cacheLoader (advanced)

The Caffeine CacheLoader that loads the value of a key that is not in the cache, for the GET and GET_ALL actions. Only used by caffeine-loadcache, which needs it to create the cache.

CacheLoader

configuration (advanced)

The shared configuration that each endpoint of this component starts from; the options of the endpoint override it.

CaffeineConfiguration

removalListener (advanced)

A Caffeine RemovalListener that the cache notifies each time an entry is removed, whether it was invalidated, replaced, evicted or expired. Caffeine calls it asynchronously after the removal, and only logs the exceptions it throws.

RemovalListener

statsCounter (advanced)

A Caffeine StatsCounter that records the statistics of the cache instead of the default counter of Caffeine. Only used when statsEnabled is true.

StatsCounter

statsEnabled (advanced)

Whether the cache records statistics (Caffeine recordStats), such as the hit and miss counts that Cache.stats() returns. Recording them costs some performance on each cache operation.

false

boolean

valueType (advanced)

The fully qualified class name of the type that the PUT action converts the message body to before it stores it as the value. When not set, the body is stored as it is. Not used when the CamelCaffeineValue header gives the value.

String

Endpoint Options

The Caffeine LoadCache endpoint is configured using URI syntax:

caffeine-loadcache:cacheName

With the following path and query parameters:

Path Parameters

Name Description Default Type

cacheName (producer)

Required The name of the cache: a Caffeine LoadingCache bean with this name in the registry, or else the cache that the component creates with this name when createCacheIfNotExist is true.

String

Query Parameters

Name Description Default Type

action (producer)

The action to perform when the message has no CamelCaffeineAction header. When neither sets an action, the exchange fails.

Enum values:

  • GET

  • GET_ALL

  • PUT

  • PUT_ALL

  • INVALIDATE

  • INVALIDATE_ALL

  • CLEANUP

  • AS_MAP

String

createCacheIfNotExist (producer)

Whether the component creates the cache when the registry has no cache bean with the cache name. The component keeps the caches it creates by name, so the endpoints with the same cache name share one cache, which the options of the first of these endpoints to start configure. The cache options (evictionType, maximumSize and the others) only apply to a cache that the component creates. When false and the registry has no such bean, the endpoint fails to start.

true

boolean

evictionType (producer)

Which options configure the eviction of the cache: SIZE_BASED uses initialCapacity and maximumSize, and TIME_BASED uses expireAfterAccessTime and expireAfterWriteTime. The options of the other type are ignored.

Enum values:

  • SIZE_BASED

  • TIME_BASED

SIZE_BASED

EvictionType

expireAfterAccessTime (producer)

The time in seconds after the last read or write of an entry, or its creation, after which Caffeine removes the entry from the cache (Caffeine expireAfterAccess). With 0, entries expire right away. Only used when evictionType is TIME_BASED, together with expireAfterWriteTime: an entry expires at the first of the two times.

300

int

expireAfterWriteTime (producer)

The time in seconds after the creation of an entry, or the last replacement of its value, after which Caffeine removes the entry from the cache (Caffeine expireAfterWrite). With 0, entries expire right away. Only used when evictionType is TIME_BASED, together with expireAfterAccessTime: an entry expires at the first of the two times.

300

int

initialCapacity (producer)

The minimum total size of the internal data structures of the cache (Caffeine initialCapacity). A large enough estimate avoids resizing later, but a too large value wastes memory. Only used when evictionType is SIZE_BASED; when not set, Caffeine uses its default.

Integer

key (producer)

The key of the entry for the GET, PUT and INVALIDATE actions when the message has no CamelCaffeineKey header. When neither sets a key, these actions fail.

String

maximumSize (producer)

The maximum number of entries the cache may contain (Caffeine maximumSize). As the size grows close to the maximum, Caffeine evicts the entries that are less likely to be used again, and it may evict an entry before the limit is exceeded or exceed it for a short time while evicting. With 0, Caffeine evicts each entry right after it is stored. Only used when evictionType is SIZE_BASED; when not set, the size of the cache has no limit.

Integer

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

cacheLoader (advanced)

The Caffeine CacheLoader that loads the value of a key that is not in the cache, for the GET and GET_ALL actions. Only used by caffeine-loadcache, which needs it to create the cache.

CacheLoader

removalListener (advanced)

A Caffeine RemovalListener that the cache notifies each time an entry is removed, whether it was invalidated, replaced, evicted or expired. Caffeine calls it asynchronously after the removal, and only logs the exceptions it throws.

RemovalListener

statsCounter (advanced)

A Caffeine StatsCounter that records the statistics of the cache instead of the default counter of Caffeine. Only used when statsEnabled is true.

StatsCounter

statsEnabled (advanced)

Whether the cache records statistics (Caffeine recordStats), such as the hit and miss counts that Cache.stats() returns. Recording them costs some performance on each cache operation.

false

boolean

valueType (advanced)

The fully qualified class name of the type that the PUT action converts the message body to before it stores it as the value. When not set, the body is stored as it is. Not used when the CamelCaffeineValue header gives the value.

String

Message Headers

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

Name Description Default Type

CamelCaffeineAction (producer)

Constant: ACTION

The action to perform, which takes precedence over the action option. Possible values: CLEANUP PUT PUT_ALL GET GET_ALL INVALIDATE INVALIDATE_ALL AS_MAP.

String

CamelCaffeineActionHasResult (producer)

Constant: ACTION_HAS_RESULT

Whether the action has put a result in the message body: true for GET when the key has a value, and for GET_ALL and AS_MAP; false for the other actions.

Boolean

CamelCaffeineActionSucceeded (producer)

Constant: ACTION_SUCCEEDED

Set to true when the action has completed. A failing action fails the exchange instead.

Boolean

CamelCaffeineKey (producer)

Constant: KEY

The key of the entry for GET, PUT and INVALIDATE, which takes precedence over the key option. The key is converted to a String.

CamelCaffeineKeys (producer)

Constant: KEYS

The Set of the keys to get for GET_ALL, which gets no entries without it, and of the keys to invalidate for INVALIDATE_ALL, which invalidates all the entries without it. AS_MAP sets it to the keys of the cache.

Set

CamelCaffeineValue (producer)

Constant: VALUE

The value to store for PUT, or a Map of the entries to store for PUT_ALL. When not set, the message body is used.

CamelCaffeineOldValue (producer)

Constant: OLD_VALUE

Not set by any action of this component.

Message Body

The message body at each side of the Caffeine LoadCache 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

Producer input

any

The value to store for PUT, converted to the valueType when set, and a Map of the entries for PUT_ALL, unless the CamelCaffeineValue header gives it; without either they fail. The other actions do not use the body.

Producer output

unknown

By the action, which the CamelCaffeineAction header can set: the value of the key for GET, from the cache or else the cacheLoader, or the body as it was when the loader gives null, a Map of the entries found or loaded for GET_ALL, and the cache as a Map for AS_MAP. The other actions keep the body.

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

  • With action=AS_MAP: map (java.util.concurrent.ConcurrentMap)

  • With action=PUT: unchanged

  • With action=PUT_ALL: unchanged

  • With action=INVALIDATE: unchanged

  • With action=INVALIDATE_ALL: unchanged

  • With action=CLEANUP: 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

A loading cache has a cacheLoader, which makes the value of a key that is not in the cache yet. The first GET of a key calls the loader, and the next GETs of that key get the value from the cache. The cache is shared by name, so all caffeine-loadcache:prices endpoints use the same cache.

In this example, the loader is a Groovy closure, and the key comes from the CamelCaffeineKey header:

- beans:
    - name: priceLoader
      type: com.github.benmanes.caffeine.cache.CacheLoader
      scriptLanguage: groovy
      script: "{ key -> 'price of ' + key } as com.github.benmanes.caffeine.cache.CacheLoader"
- route:
    from:
      uri: direct:price
      steps:
        - setHeader:
            name: CamelCaffeineKey
            expression:
              simple:
                expression: "${header.product}"
        - to:
            uri: caffeine-loadcache:prices
            parameters:
              action: GET
              cacheLoader: "#priceLoader"
        - log:
            message: "${body}"

The operations and their result headers are the same as for the Caffeine Cache component.