Maven – Spring – Ehcache
Objective: Creating a Spring based application, with caching [using ehcache].
Cache is a component that transparently stores data in such a way that any future request to this data could be served faster without fetching from the original source again.
Ehcache can be used for
- general purpose caching as we are going to see in this example,
- in a second level cache in hibernate[ not explained here ].
- Physical implementation is either in-memory or on disk.
- Logical representation is through the classes provided by ehcache.jar
Basically, Ehcache consists of CacheManager, which manages cache [Creation/Access-to/Removal of cache]
Cache contain ‘Elements’ which are key-value pairs.
Let’s learn by hands-on.
I am going to create a Maven Spring project in eclipse IDE, and we see how to use ehcache to cache the data, and the configuration involved in the process. I am keeping this example to have components that are required only to demonstrate our goal [no unnecessary jars]
– Create a maven project in eclipse
Let us add spring and ehcache dependencies to our project by adding them to pom.xml
How do you get the dependency?
Just Search on the maven repository ..
A snapshot of the Maven dependencies after adding the dependencies in pom.xml, looks like below:
Note: Sometimes if this doesn’t get refreshed automatically , please do a maven command to sync maven and eclipse using the maven command ‘mvn eclipse:eclipse’
- First Create a spring configuration file to define your beans
- Note: we will add more xsd as we proceed further to support required bean and tags.
In this tutorial, we use @Cacheable annotation to mark a bean as cacheable.
@Cacheable annotation requires spring-context [any version]
To use @Cacheable annotation, you have to use Spring version 3.1.x +
I decided to use 3.2.6.RELEASE
Adding spring-context dependency to pom.xml added a total of five jars to Maven dependency:
- Note: It’s time to add one more dependency.
The org.springframework.cache.ehcache.EhCacheCacheManager bean is not found so far.
Infact, the org.springframework.cache.ehcache package is not found
Add the following dependency to resolve the same: [This is from my practical experience. You can remove this dependency and test it]
Now that all dependencies and configuration is set, we will look at the complete project :
You could see, this is what happens:-
- First time, when getEmployees() is called, the actual method inside the DAO is executed, list is created and returned.
- On the subsequent calls, the list of employee is retrieved from the cache.
- First time, when getEmployee() with the name “Harley” is called, getEmployee() in the DAO is executed and the employee is retrieved.
- On the subsequent calls, the employee is retrieved from the cache.
We are done.. Happy Learning 🙂
Going further to the details:
- All the attributes that could be used in cache in ehcache configuration file are well explained in the section ‘Cache configuration’ in this documentation of ehcache. http://ehcache.org/ehcache.xml
In spring-config.xml, we have configured the ehcache bean :
<bean id=”ehcache” class=”org.springframework.cache.ehcache.EhCacheManagerFactoryBean”>
<property name=”configLocation” value=”classpath:ehcache.xml” />
This bean has two properties:
- configLocation – Optional.
- Used to specify location of ehcache configuration file.
- Default is “ehcache.xml” in the root of the class path, or if not found, refers “ehcache-failsafe.xml” in the EhCache jar (default EhCache initialization)
- Shared – Optional.
- As per the documentation from ‘org.springframework.cache.ehcache’, it states
“Set whether the EhCache CacheManager should be shared (as a singleton at the VM level) or independent (typically local within the application).
Default is “false”, creating an independent instance.”
Note: A mistake that can happen while invoking the method that is cached.
Note: There is a common mistake that could happen here,
EmployeeDAO dao = (EmployeeDAO)context.getBean(“employeeDAO”);
Instead of getting the EmployeeDAO from the context, if you try to create one using the new operator,the caching WONT work. Guess why?.. The EmployeeDAO will not get the spring annotations applied because it is not spring-managed.
EmployeeDAO dao = new EmployeeDAO();
dao.getEmployees(); // caching doesn’t work as the DAO bean creation is not spring managed
Things to try out
– We can use custom annotations
- There are many more attributes that can be used to define a cache in the file ehcache.xml
- Also read https://www.ehcache.org/documentation/3.8/getting-started.html
- Try changing ‘maxElementsInMemory’ with ‘maxEntriesLocalHeap’
- Another way of setting the property of cacheManager. Note the ‘p:cache-manager-ref‘
<bean id=”cacheManager” class=”org.springframework.cache.ehcache.EhCacheCacheManager”
- Note to use xmlns:p=”http://www.springframework.org/schema/p”
- Also in pom.xml , you might have to use the dependency for spring-context-support
Source code: https://github.com/codinko/ehcache-spring
More to learn/read-on:
http:// www.javacreed.com/ caching-made-easy-with-spring/
http:// viralpatel.net/blogs/ cache-support-spring-3-1-m1/
Related SO qn: