Tuesday, January 14, 2014

Configure Ehcache as a Second Level Cache

Overview


Terracotta Ehcache is a popular open source Java cache that can be used as a Hibernate second level cache.  It can be used as a standalone second level cache, or can be configured for clustering to provide a replicated coherent second level cache.

Installation


Hibernate ships with the ehcache library. Hibernate 3.5 will ship with Ehcache 1.5. Ehcache 2.0 came out too close to the final ship date for Hibernate 3.5, but we will update it to 2.0 in the next release of Hibernate. In the meantime, to use the new Ehcache provider you need to download it or, if you are using Maven, add it as a dependency. To download Ehcache, visit the Terracotta Ehcache download site:


The Maven snippet is for Ehcache 2.0 and any upgrades is:

  1.         <dependency>  
  2.             <groupId>net.sf.ehcache</groupId>  
  3.             <artifactId>ehcache</artifactId>  
  4.             <version>[2.0.0,]</version>  
  5.             <type>pom</type>  
  6.         </dependency>  


Configuration


The Hibernate documentation Chapter 19.2 provides detailed information on configuring the Hibernate second level cache.  A brief overview of the steps is provided here for reference.

Step 1 - Configure Hibernate


First, configure Hibernate for second level caching and specify the second level cache provider:  Hibernate 3.3 introduced a new second level caching SPI, so if you are using Hibernate 3.3 or greater, be sure to take advantage of the new interface by selecting the appropriate configuration depicted below.

Hibernate 3.3 and above

  1. <property key="hibernate.cache.use_second_level_cache">true</property>  
  2. <property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>  

Hibernate 3.2

  1. <property key="hibernate.cache.use_second_level_cache">true</property>  
  2. <property name="hibernate.cache.region.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>  

Step 2 - Configure your entities, collections, and queries for caching


Next, update your hibernate configuration to configure entities, collections for caching.  To enable queries to be cached, you will need to update the code where the query is created to set caching enabled.

Cache Strategy

Before you configure caching for entities and collections, decide on the proper caching strategy to be used.  You may select from:

  • read-only
  • read-write
  • nonstrict-read-write

Upcoming versions of Ehcache will also support the transactional strategy.
Entities

Configure entities to be cached using the cache strategy setting in hbm.xml:


  1. <class name="com.mypackage.MyEntity" table="...">  
  2.     <cache usage="read-write"/>  
  3. </class>  


Users of Java 5.0 Annotation based configuration will configure caching on the class definition itself using the @Cache annotation:


  1. @Entity  
  2. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
  3. public class MyEntity {  
  4.     ...  
  5. }  

Collections

Configure collections to be cached using the cache strategy setting in hbm.xml:

  1. <class name="com.mypackage.MyEntity" table="...">  
  2.     <cache usage="read-write"/>  
  3.      <set name="mySet">  
  4.          <cache usage="read-write"/>  
  5.     </set>  
  6. </class>  


Users of Java 5.0 Annotation based configuration will configure caching on the class definition itself using the @Cache annotation:

  1. @Entity  
  2. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)public class MyEntity {    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)    Set mySet = ...;    ...}  
Query caching

You can also enable query caching.  To do so configure it in your hbm.xml:

  1. <property key="hibernate.cache.use_query_cache">true</property>  


Then, where queries are defined in your code, add the method call setCacheable(true) to the queries that should be cached:

  1. return sessionFactory.getCurrentSession().createQuery("...").setCacheable(true).list();    

Step 3 - (Optional) Configure ehcache.xml


By default, Ehcache will create separate cache regions for each entity that you configure for caching.  You can change the defaults for these regions by adding the configuration to your ehcache.xml, an example is provided here:

  1. <cache  
  2.     name="com.somecompany.someproject.domain.Country"  
  3.     maxElementsInMemory="10000"  
  4.     eternal="false"  
  5.     timeToIdleSeconds="300"  
  6.     timeToLiveSeconds="600"  
  7.     overflowToDisk="true"  
  8. />  


Step 4 - (Optional) Configure for clustered caching

Ehcache can be configured for clustered caching using the Terracotta platform.  Detailed instructions for installing and setting up Terracotta Ehcache as a clustered Hibernate second level cache are provided at terracotta.org.

If you downloaded Ehcache using the link above, you already have Terracotta installed.  Getting started with a clustered cache is very easy.   First, tell Ehcache to cluster your cache using Terracotta by adding the element to your cache definition:

  1. <cache  
  2.     name="com.somecompany.someproject.domain.Country"  
  3.     maxElementsInMemory="10000"  
  4.     eternal="false"  
  5.     timeToIdleSeconds="300"  
  6.     timeToLiveSeconds="600"  
  7.     overflowToDisk="true">  
  8.     <terracotta/>  
  9. </cache>  

Then, before starting your hibernate application with Ehcache, make sure at least one Terracotta server is running:

$ start-tc-server.sh


You can monitor the status of your clustered cache and view all of the Hibernate Metrics using the Terracotta Developer Console included with the Terracotta installation:

$ dev-console.sh

More Information


For more information on configuring Ehcache as a Hibernate second level cache, see:

No comments: