Over a million developers have joined DZone.

Implementing Ehcache using Spring context and Annotations

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

Part 1 – Configuring Ehcache with Spring

Ehcache is most widely used open source cache for boosting performance, offloading your database, and simplifying scalability. It is very easy to configure Ehcache with Spring context xml. Assuming you have a working Spring configured application, here we discuss how to integrate Ehcache with Spring.

In order to configure it, we need to add a CacheManager into the Spring context file. Code snippet added below

<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:EhCache.xml" p:shared="true"/>
	  
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache"/>

In ‘ehcache’ bean, we are referring to ‘Ehcache.xml’ file which will contain all ehcache configurations. Sample ehcache file is added below. You can configure this file according to your project needs.

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

<ehcache>
	 <defaultCache
		 maxEntriesLocalHeap="10000"
		 eternal="false"
		 timeToIdleSeconds="120"
		 timeToLiveSeconds="120"
		 maxEntriesLocalDisk="100000"
		 diskExpiryThreadIntervalSeconds="120"
		 memoryStoreEvictionPolicy="LRU">
		 <persistence strategy="localTempSwap"/>
	 </defaultCache>
	 <cache name="customer" 
	 		maxElementsInMemory="10000" 
	 		eternal="false" 
	 		timeToLiveSeconds="3600" 
	 		diskPersistent="false" 
	 		memoryStoreEvictionPolicy="LRU" 
	 		overflowToDisk="false" />
</ehcache>

Here you can two caches, defaultCache and one defined with name ‘TestCache’. DefaultCache configuration is applied to any cache that is not explicitly configured.

Part 2 - Enabling Caching Annotations

In order to used Spring provided java annotations , we need to declarative enable cache annotations in Spring config file.  Code snippet added below.

<!-- Enables caching through annotations -->

<cache:annotation-driven />

In order to use above annotation declaration, we need to add cache namespace into the spring file. Code snippet added below.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

        <cache:annotation-driven />

</beans>

Spring Annotations for caching 

  • @Cacheable triggers cache population 
  • @CacheEvict triggers cache eviction 
  • @CachePut updates the cache without interfering with the method execution 

I will give brief description and practical implementation of these annotations. For detailed explanations please refer spring documentation for caching .

@Cacheable - This annotation means that the return value of the corresponding method can be cached and multiple invocation of this method with same arguments must populate the return value from cache without executing the method. Code snippet added below.

@Cacheable("customer")
public Customer findCustomer(String custId) {...}

Each time the method is called, the cache with name ‘customer’  is checked to see whether the invocation has been already executed for the same ‘custId’. 

@CachePut  - This annotation is used to update the cache without interfering the method execution. Method will always be executed and its result will be replaced in the cache. This annoatation is used for cache population.

@CachePut("customer")
public Customer updateBook(String custId){...}

@CacheEvict – This annotation is used for cache eviction, used to remove stale or unused data from the cache.

@CacheEvict(value="customer", allEntries=true)
public void unloadCustomer(String newBatch)

With above configurations, all entries in the ‘customer’ cache will be removed. Above description will give head start to configure Ehcachewith spring and use some of the caching annotations. 

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}