Ehcache
Since Camel 2.18
Both producer and consumer are supported
The Ehcache component enables you to perform caching operations using Ehcache 3 as the Cache Implementation.
The Cache consumer is an event based consumer and can be used to listen and respond to specific cache activities.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-ehcache</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> 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,*.yamlfiles, 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 Ehcache component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
The Ehcache CacheManager to use. It takes precedence over cacheManagerConfiguration and configurationUri. Camel neither initializes nor closes it, so it must be initialized before the routes start. | CacheManager | ||
The Ehcache Configuration from which Camel creates the CacheManager, which Camel initializes and closes. Endpoints with the same Configuration share the CacheManager. Used when cacheManager is not set, and takes precedence over configurationUri. | Configuration | ||
The location of an Ehcache XML configuration file from which Camel creates the CacheManager, which Camel initializes and closes. It is loaded from the classpath by default; use the file: or http: prefix for another location. Endpoints with the same file share the CacheManager. Used when neither cacheManager nor cacheManagerConfiguration is set. Without these three options, the endpoints share one CacheManager with the default settings of Ehcache. | String | ||
Whether to create the cache when the CacheManager has no cache of that name. The cache is created with its CacheConfiguration in configurations, else with the configuration option, else with an on-heap tier and no size limit. When false and the cache does not exist, the producer or consumer fails to start. | true | boolean | |
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 | |
How Ehcache fires the cache events to the consumer: ASYNCHRONOUS, so the thread that changed the cache does not wait, or SYNCHRONOUS, so the thread that changed the cache waits until the route has processed the event. Enum values:
| ASYNCHRONOUS | EventFiring | |
The ordering of the cache events that the consumer receives: ORDERED keeps the order in which the events of each key occurred, UNORDERED may deliver them out of order. Enum values:
| ORDERED | EventOrdering | |
The types of the cache events that the consumer receives, separated by comma. When not set, the consumer receives all of them. Enum values:
| String | ||
The default cache action of the producer. The CamelEhcacheAction header takes precedence. When neither is set, the exchange fails. Enum values:
| String | ||
The default key of the cache entry for PUT, PUT_IF_ABSENT, GET, REMOVE and REPLACE. The CamelEhcacheKey header takes precedence. Unlike the header, this key is used as it is, not converted to the keyType. | Object | ||
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 | |
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 | |
The CacheConfiguration (key and value types, ResourcePools, expiry) used to create a cache that the CacheManager does not have, when createCacheIfNotExist is true and configurations has no entry for the cache name. Its key and value types are used when keyType and valueType are not set. | CacheConfiguration | ||
The CacheConfigurations by cache name, used to create a cache that the CacheManager does not have, when createCacheIfNotExist is true. The entry of the cache name takes precedence over the configuration option, and its key and value types are used when keyType and valueType are not set. | Map | ||
The fully qualified class name of the keys of the cache, such as java.lang.String. The producer converts the CamelEhcacheKey header to this type. When not set, the key type of the CacheConfiguration of the cache is used, else java.lang.Object. The cache is looked up with this type: it must be the key type of a cache that the CacheManager already has, or the producer or consumer fails to start. | String | ||
The fully qualified class name of the values of the cache, such as java.lang.String. The producer converts the message body to this type for PUT, PUT_IF_ABSENT and REPLACE. When not set, the value type of the CacheConfiguration of the cache is used, else java.lang.Object. The cache is looked up with this type: it must be the value type of a cache that the CacheManager already has, or the producer or consumer fails to start. | String |
Endpoint Options
The Ehcache endpoint is configured using URI syntax:
ehcache:cacheName
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The Ehcache CacheManager to use. It takes precedence over cacheManagerConfiguration and configurationUri. Camel neither initializes nor closes it, so it must be initialized before the routes start. | CacheManager | ||
The Ehcache Configuration from which Camel creates the CacheManager, which Camel initializes and closes. Endpoints with the same Configuration share the CacheManager. Used when cacheManager is not set, and takes precedence over configurationUri. | Configuration | ||
The location of an Ehcache XML configuration file from which Camel creates the CacheManager, which Camel initializes and closes. It is loaded from the classpath by default; use the file: or http: prefix for another location. Endpoints with the same file share the CacheManager. Used when neither cacheManager nor cacheManagerConfiguration is set. Without these three options, the endpoints share one CacheManager with the default settings of Ehcache. | String | ||
Whether to create the cache when the CacheManager has no cache of that name. The cache is created with its CacheConfiguration in configurations, else with the configuration option, else with an on-heap tier and no size limit. When false and the cache does not exist, the producer or consumer fails to start. | true | boolean | |
How Ehcache fires the cache events to the consumer: ASYNCHRONOUS, so the thread that changed the cache does not wait, or SYNCHRONOUS, so the thread that changed the cache waits until the route has processed the event. Enum values:
| ASYNCHRONOUS | EventFiring | |
The ordering of the cache events that the consumer receives: ORDERED keeps the order in which the events of each key occurred, UNORDERED may deliver them out of order. Enum values:
| ORDERED | EventOrdering | |
The types of the cache events that the consumer receives, separated by comma. When not set, the consumer receives all of them. Enum values:
| String | ||
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 | |
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 | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
The default cache action of the producer. The CamelEhcacheAction header takes precedence. When neither is set, the exchange fails. Enum values:
| String | ||
The default key of the cache entry for PUT, PUT_IF_ABSENT, GET, REMOVE and REPLACE. The CamelEhcacheKey header takes precedence. Unlike the header, this key is used as it is, not converted to the keyType. | Object | ||
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 | |
The CacheConfiguration (key and value types, ResourcePools, expiry) used to create a cache that the CacheManager does not have, when createCacheIfNotExist is true and configurations has no entry for the cache name. Its key and value types are used when keyType and valueType are not set. | CacheConfiguration | ||
The CacheConfigurations by cache name, used to create a cache that the CacheManager does not have, when createCacheIfNotExist is true. The entry of the cache name takes precedence over the configuration option, and its key and value types are used when keyType and valueType are not set. | Map | ||
The fully qualified class name of the keys of the cache, such as java.lang.String. The producer converts the CamelEhcacheKey header to this type. When not set, the key type of the CacheConfiguration of the cache is used, else java.lang.Object. The cache is looked up with this type: it must be the key type of a cache that the CacheManager already has, or the producer or consumer fails to start. | String | ||
The fully qualified class name of the values of the cache, such as java.lang.String. The producer converts the message body to this type for PUT, PUT_IF_ABSENT and REPLACE. When not set, the value type of the CacheConfiguration of the cache is used, else java.lang.Object. The cache is looked up with this type: it must be the value type of a cache that the CacheManager already has, or the producer or consumer fails to start. | String |
Message Headers
The Ehcache component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The cache action to perform: CLEAR, PUT, PUT_ALL, PUT_IF_ABSENT, GET, GET_ALL, REMOVE, REMOVE_ALL or REPLACE. It takes precedence over the action option. | String | |
CamelEhcacheActionHasResult (common) Constant: | Set by the producer: true when the action returned a value, which is the value of the key in the body for GET, the Map in the body for GET_ALL (also when empty), and the previous value of the key in the CamelEhcacheOldValue header for PUT_IF_ABSENT and for REPLACE without that header. | Boolean | |
CamelEhcacheActionSucceeded (common) Constant: | Set by the producer: false when a REMOVE or REPLACE with the CamelEhcacheOldValue header left the entry as it was, because the key was not mapped to that value; true otherwise, also when GET found no value or REPLACE without that header found no entry. | Boolean | |
| Constant: | The key of the cache entry. The producer uses it for PUT, PUT_IF_ABSENT, GET, REMOVE and REPLACE, converted to the keyType when set, and it takes precedence over the key option. The consumer sets it to the key of the entry of the event. | Object | |
| Constant: | The keys for GET_ALL and REMOVE_ALL. When not set, these actions use no key. | Set | |
| Constant: | The value to store for PUT, PUT_IF_ABSENT and REPLACE, or the Map of the entries for PUT_ALL. It takes precedence over the message body, and is stored as it is, not converted to the valueType. | Object | |
| Constant: | For REMOVE and REPLACE, the value that the key must be mapped to for the entry to be removed or replaced. The producer sets it to the value the key already had for PUT_IF_ABSENT (which then stores nothing), and to the replaced value for REPLACE without this header. The consumer sets it to the value of the entry before the event, null for CREATED. | Object | |
CamelEhcacheEventType (common) Constant: | The type of the cache event that the consumer received: CREATED, UPDATED, REMOVED, EXPIRED or EVICTED. Enum values:
| EventType |
Message Body
The message body at each side of the Ehcache 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 |
| The new value of the entry, as it was put, with the key in the CamelEhcacheKey header, the event in CamelEhcacheEventType and the previous value in CamelEhcacheOldValue. A REMOVED, EXPIRED or EVICTED event has no body. |
Producer input |
| The value to store for PUT, PUT_IF_ABSENT and REPLACE, converted to the valueType when set, and a Map of the entries for PUT_ALL, unless the CamelEhcacheValue header gives it. The value is stored as it is: a stream is read once, so convert it to text or bytes first. The other actions do not use the body. |
Producer output |
| By the action, which the CamelEhcacheAction header can set: the value of the key for GET, or the body as it was when the key is not in the cache, and for GET_ALL a Map of the keys in the CamelEhcacheKeys header to their values, null for a key not found. The other actions keep the body; PUT_IF_ABSENT and REPLACE put the previous value in the CamelEhcacheOldValue header.
|
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.
Examples
Using the cache in a route
The producer runs the action of the CamelEhcacheAction header (or of the action option) with the key of the CamelEhcacheKey header. A PUT stores the message body. A GET sets the value as the message body, and the header CamelEhcacheActionHasResult tells whether the key was found:
- route:
from:
uri: direct:save-order
steps:
- setHeader:
name: CamelEhcacheAction
expression:
constant:
expression: PUT
- setHeader:
name: CamelEhcacheKey
expression:
simple:
expression: "${header.orderId}"
- to:
uri: ehcache:orders
- route:
from:
uri: direct:find-order
steps:
- setHeader:
name: CamelEhcacheAction
expression:
constant:
expression: GET
- setHeader:
name: CamelEhcacheKey
expression:
simple:
expression: "${header.orderId}"
- to:
uri: ehcache:orders
- choice:
when:
- expression:
simple:
expression: "${header.CamelEhcacheActionHasResult}"
steps:
- log:
message: "Order ${header.orderId} from the cache: ${body}"
otherwise:
steps:
- log:
message: "Order ${header.orderId} is not in the cache" Endpoints without a cacheManager, cacheManagerConfiguration or configurationUri share one CacheManager per component. ehcache:orders?action=PUT and ehcache:orders?action=GET use the same cache, and all endpoints for the same cache name must use the same keyType and valueType. A cache created on demand has no size limit; use a cache configuration or configurationUri to bound it or to set an expiry. |
The consumer receives cache events for caches created on demand in the shared manager. In this example, both endpoints use the same ehcache.xml for a custom capacity or expiry:
- route:
from:
uri: direct:save-order
steps:
- setHeader:
name: CamelEhcacheKey
expression:
simple:
expression: "${header.orderId}"
- to:
uri: ehcache:orders
parameters:
configurationUri: classpath:ehcache.xml
action: PUT
- route:
from:
uri: ehcache:orders
parameters:
configurationUri: classpath:ehcache.xml
eventTypes: CREATED
steps:
- log:
message: "New order ${header.CamelEhcacheKey}: ${body}" The ehcache.xml file configures the cache:
<config xmlns="http://www.ehcache.org/v3">
<cache alias="orders">
<heap unit="entries">1000</heap>
</cache>
</config> Ehcache based idempotent repository example:
CacheManager manager = CacheManagerBuilder.newCacheManager(new XmlConfiguration("ehcache.xml"));
EhcacheIdempotentRepository repo = new EhcacheIdempotentRepository(manager, "idempotent-cache");
from("direct:in")
.idempotentConsumer(header("messageId"), repo)
.to("mock:out"); Ehcache based aggregation repository example:
public class EhcacheAggregationRepositoryRoutesTest extends CamelTestSupport {
private static final String ENDPOINT_MOCK = "mock:result";
private static final String ENDPOINT_DIRECT = "direct:one";
private static final int[] VALUES = generateRandomArrayOfInt(10, 0, 30);
private static final int SUM = IntStream.of(VALUES).reduce(0, (a, b) -> a + b);
private static final String CORRELATOR = "CORRELATOR";
@EndpointInject(ENDPOINT_MOCK)
private MockEndpoint mock;
@Produce(uri = ENDPOINT_DIRECT)
private ProducerTemplate producer;
@Test
public void checkAggregationFromOneRoute() throws Exception {
mock.expectedMessageCount(VALUES.length);
mock.expectedBodiesReceived(SUM);
IntStream.of(VALUES).forEach(
i -> producer.sendBodyAndHeader(i, CORRELATOR, CORRELATOR)
);
mock.assertIsSatisfied();
}
private Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
} else {
Integer n = newExchange.getIn().getBody(Integer.class);
Integer o = oldExchange.getIn().getBody(Integer.class);
Integer v = (o == null ? 0 : o) + (n == null ? 0 : n);
oldExchange.getIn().setBody(v, Integer.class);
return oldExchange;
}
}
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from(ENDPOINT_DIRECT)
.routeId("AggregatingRouteOne")
.aggregate(header(CORRELATOR))
.aggregationRepository(createAggregateRepository())
.aggregationStrategy(EhcacheAggregationRepositoryRoutesTest.this::aggregate)
.completionSize(VALUES.length)
.to("log:org.apache.camel.component.ehcache.processor.aggregate.level=INFO&showAll=true&mulltiline=true")
.to(ENDPOINT_MOCK);
}
};
}
protected EhcacheAggregationRepository createAggregateRepository() throws Exception {
CacheManager cacheManager = CacheManagerBuilder.newCacheManager(new XmlConfiguration("ehcache.xml"));
cacheManager.init();
EhcacheAggregationRepository repository = new EhcacheAggregationRepository();
repository.setCacheManager(cacheManager);
repository.setCacheName("aggregate");
return repository;
}
}