Over a million developers have joined DZone.

Transactional Caching for Camel With Infinispan

DZone's Guide to

Transactional Caching for Camel With Infinispan

· Integration Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Some time ago I created a Redis connector for Camel. Redis is an awesome key-value store (and a lot more) but then I needed a cache running in the same JVM as Camel and noticed Infinispan, which has just switched to ASL v2. There are already other connectors in Camel for caching on the JVM, like Hazelcast and EHCache, but if you are already using Camel as part of other Red Hat products or want to see how LIRS eviction overperforms LRU, Infinispan is worth trying.

Briefly, Infinispan is transactional in-memory key-value store and data grid. When used in embedded mode, Infinispan resides in the same JVM as Camel and allows Camel consumer to receive cache change notifications:

  <from uri="infinispan://localhost?cacheContainer=#cacheContainer&caseName=orders&eventTypes=CACHE_ENTRY_CREATED"/>
    <simple>${out.header.CamelInfinispanIsPre} == true</simple>
    <to uri="log:com.mycompany.order?showHeaders=true"/>

In the example above, when a cache entry is created, Infinispan will fire two events - one before and one after the cache entry has been created. It is also possible to receive the events synchronously, meaning in the same thread that processes the cache action, or asynchronously in a separate thread without blocking the cache action.

Using Infinispan as a local cache is simple, it exposes a ConcurrentMap interface and has the usual expiration, eviction, passivation, persistent store, querying, etc features. What makes Infinispan also a data grid is the ability of the nodes to discover other nodes and replicate or distribute data among themselves. Replication allows sharing data across a cluster whereas distribution uses consistent hashing algorithm to achieve better scalability.
In client-server mode, Infinispan is running as standalone application, and Camel producer can send messages using Infinispan's Hot Rod client. Hot Rod is a binary, language neutral, intelligent protocol, allowing interaction with Infinisnap servers in topology and hash-distribution-aware fashion.

The Infinispan producer in Camel currently offers GET, PUT, REMOVE and CLEAR operations. Here is an example of the producer putting data to orders cache:

  <from uri="direct:orderCache"/>
  <setHeader headerName="CamelInfinispanKey">
  <setHeader headerName="CamelInfinispanValue">
  <setHeader headerName="CamelInfinispanOperation">
  <to uri="infinispan://localhost?caseName=orders"/>

Let's create a more interesting example. Infinispan is also JTA compliant and can participate in transactions. We will create a REST API for registering persons, which will first persist the person in a relational database using Camel sql component, and then will put the firstName into Infinispan cache in the same transaction. We will do that using a transacted Camel route, so if an error occurs during routing, at any stage, Camel will make sure the transaction(for the cache and the database) is rolled back, so that the database and the cache are always in a consistent state.

  <from uri="restlet:/persons?restletMethod=POST"/>

  <!-- PERSIST TO DB -->
  <to uri="sql:insert into person(firstName, lastName) values(:#firstName,:#lastName)?dataSource=#dataSource"/>

    <simple>${in.header.lastName} == "damn"</simple>
    <throwException ref="damn"/>

  <!-- PUT TO CACHE -->
  <to uri="sql:select id from person WHERE id = (select max(id) from person)?dataSource=#dataSource"/>
  <setHeader headerName="personId">
  <setHeader headerName="CamelInfinispanKey">
    <simple>${headerAs(personId, String)}</simple>
  <setHeader headerName="CamelInfinispanValue">
  <setHeader headerName="CamelInfinispanOperation">
  <to uri="infinispan://localhost?cacheContainer=#cacheContainer&caseName=orders"/>

As you can see there is no magic or extra configuration in the route, it is a standard route. We have small bit of code that throws an exception when the person lastName is damn to simulate errors in the middle of the route.

The application runs in a standalone mode with atomikos JTA transaction manager. First we create a JtaTransactionManager

<bean id="userTransaction" class="com.atomikos.icatch.jta.UserTransactionImp"/>
<bean id="userTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"/>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> 
  <constructor-arg ref="userTransaction"/>
  <constructor-arg ref="userTransactionManager"/>

Then wrap our DataSource with it:

public AtomikosDataSourceBean atomikosDataSourceBean() throws Exception {
    EmbeddedXADataSource ds = new EmbeddedXADataSource();
    AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
    return xaDataSource;

and using a TransactionManagerLookup tell Infinispan to participate in the same transaction:

public BasicCacheContainer basicCacheContainer() throws Throwable {
    GlobalConfiguration glob = new GlobalConfigurationBuilder().nonClusteredDefault().build();

    Configuration loc = new ConfigurationBuilder()
        .transactionManagerLookup(new TransactionManagerLookup() {
            public TransactionManager getTransactionManager() throws Exception {
            return jtaTransactionManager.getTransactionManager();

    return new DefaultCacheManager(glob, loc, true);

After all this boilerplate code, we have our datasource, cache and Camel route participating in the same transaction. To see the full REST example with two phase commit and rollback, get the source code from github and play with it.

BTW, the Camel-infinispan component is still not part of Camel trunk, to run the example you will need that too.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}