Quick Start

 

Products & Services

 

Training Dates

US - San Francisco
Oct 6-7, 2010
Nov 11-12, 2010
Dec 2-3, 2010
Feb 4-5, 2011

India - Delhi
Dec 2-3, 2010

See training details.

 

Blogs & Tweets

Using Grails and Ehcache

Using Ehcache as a Second Level Caching Provider for Hibernate within Grails

Grails 1.2RC1 and higher use Ehcache as the default Hibernate second level cache. However earlier versions of Grails ship with the Ehcache library and are very simple to enable.

The following steps show how to configure Grails to use Ehcache. For 1.2RC1 and higher some of these steps are already done for you.

Configuring Ehcache as the second level Hibernate cache

Edit DataSource.groovy as follows:

    hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=true
    cache.provider_class='org.hibernate.cache.EhCacheProvider'
}

Overriding defaults by specifying cache configurations

As is usual with Hibernate, it will use the defaultCache configuration as a template to create new caches as required. For production use you often want to customise the cache configuration. To do so, add an ehcache.xml configuration file to the conf directory (the same directory that contains DataSource.groovy).

A sample ehcache.xml which works with the Book demo app and is good as a starter configuration for Grails is shown below:

<?xml version="1.0" encoding="UTF-8"?>

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd" >

    <diskStore path="java.io.tmpdir"/>

    <cacheManagerEventListenerFactory class="" properties=""/>


    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            />

    <cache name="Book"
           maxElementsInMemory="10000"
           timeToIdleSeconds="300"
            />

    <cache name="org.hibernate.cache.UpdateTimestampsCache"
           maxElementsInMemory="10000"
           timeToIdleSeconds="300"
            />

    <cache name="org.hibernate.cache.StandardQueryCache"
           maxElementsInMemory="10000"
           timeToIdleSeconds="300"
            />



</ehcache>

Springcache Plugin

The Springcache plugin allows you to easily add the following functionality to your Grails project:

  • Caching of Spring bean methods (typically Grails service methods).
  • Caching of page fragments generated by Grails controllers.
  • Cache flushing when Spring bean methods or controller actions are invoked.

    The plugin depends on the EhCache and EhCache-Web libraries.

    See Springcache Plugin}, part of the Grails project for more information.

Clustering Web Sessions

This is not handled by Ehcache, but by a sister product from Terracotta, web sessions.

See http://gquick.blogspot.com/2010/03/clustering-grails-app-with-terracotta.html for a great intro on getting this going with Grails and Tomcat.