Spring Boot + EhCache Hibernate Working Example

Spring Boot + Ehcache Hibernate Working Example:

When I was trying to populate JSON records in my angular app (just 1885 records only), it took around 11 seconds and in angular side I am just populating in the datatable. So I thought to implement ehcache with spring boot to make it faster.

After implementing that successfully I am really surprised because it took around 300ms only to load same number of records (1885 records).

Also no query will run from second time, until you modify something.

Implementation steps in Overview:

1. Add org.springframework.boot and net.sf.ehcache to your pom.xml
2. Create ehcache.xml under resources folder of your spring boot project.
3. Add ehcache file to your application.properties
4. Add @EnableCaching to your spring startup java class.
5. Add @CacheConfig(cacheNames = “myCache”) to your service class.
6. Add @Cacheable(value=”myCache”) to your findAll crud repository method.
7. Add @CacheEvict for update & delete to enable the caching to take instant effect.

 

 

Detailed Steps:

1. Add org.springframework.boot and net.sf.ehcache to your pom.xml

Add the ehcache and spring boot maven dependencies to your spring boot project.

[plain]

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

[/plain]

 

 

2. Create ehcache.xml under resources folder of your spring boot project.

myCache – Name of the cache and here you can also keep timeToLiveSeconds as per your requirement to keep the cache in the memory.

here timeToLiveSeconds is 300 means 5 minutes, so every 5 mins cache will be refreshed automatically even no difference in the table values.

<?xml version=”1.0″ encoding=”UTF-8″?>
<ehcache xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:noNamespaceSchemaLocation=”http://www.ehcache.org/ehcache.xsd”
updateCheck=”true”
monitoring=”autodetect”
dynamicConfig=”true”>

<cache name=”myCache”
maxElementsInMemory=”100″
eternal=”false”
overflowToDisk=”false”
timeToLiveSeconds=”300″
timeToIdleSeconds=”0″
memoryStoreEvictionPolicy=”LFU”
transactionalMode=”off”>
</cache>

</ehcache>

 

3. Add ehcache file to your application.properties

Add the below lines to your application.properties to load the ehcache. This loads ehcache also while loading the application.properties.
[plain]
spring.cache.ehcache.config=classpath:ehcache.xml
spring.jpa.properties.javax.persistence.sharedCache.mode=ALL
[/plain]

 

 

4. Add @EnableCaching to your spring startup java class.

Here MySpringBootApplication is a spring boot class where it starts its execution. Add @EnableCaching annotation to let spring boot to know to load cache as well while starting the application.

[java]

@EnableCaching
@SpringBootApplication
public class MySpringBootApplication {

public static void main(String[] args) {
SpringApplication.run(CouponzcornerBackendApplication.class, args);
}
}

[/java]

 

 

5. Add @CacheConfig(cacheNames = “myCache”) to your service class.

Add @CacheConfig to your service implementation class when you have your DAO’s autowired. cacheNames here I mentioned as myCache, note the same mentioned in DAO’s also in the ehcache.xml file.

[java]

@Service
@CacheConfig(cacheNames = “myCache”)
public class MyServiceImpl implements MyService {

@Autowired
private MyFirstDao myFirstDao;

@PersistenceContext
private EntityManager entityManager;
}

[/java]

 

6. Add @Cacheable(value=”myCache”) to your findAll crud repository method.

@Cacheable annotation caches the results and will not allow to run the query until some changes found(if @cacheEvict used/timetoliveseconds expired).

[java]
@Repository
public interface MyFirstDao extends CrudRepository<MyPOJO, Long>{

@Cacheable(value=”myCache”)
List findByUser(User user);

@Cacheable(value=”myCache”)
List findAll();

@Cacheable(value = “myCache”, key = “#myId”)
MyPOJO findByMyId(Long myId);
}
[/java]

 

 

7. Add @CacheEvict/@CachePut for update & delete to enable the caching to take instant effect.

To enable cache to take the instant updates after modifying or deleting etc.

I used CacheEvict only and it worked awesome.

[java]
@Repository
public interface MyFirstDao extends CrudRepository<MyPOJO, Long>{
@CacheEvict(value=”myCache”, allEntries=true)
MyPOJO save(MyPOJO myPojo);

@CacheEvict(value = “myCache”, allEntries = true)
void deleteAll();

@CacheEvict(value=”myCache”, allEntries=true)
@Transactional
void deleteByCouponId(Long myId);
}
[/java]

 

 

How to Confirm whether ehcache works or not ?

1. Enable “spring.jpa.show-sql=true” so that it will print all the queries when it loads first time.
2. If the ehCache works fine, then from second time till the time to live seconds alive it won’t load or print the queries again, until and unless you perform some delete or update functionalities.
3. If you do not want cache to refresh on performing update or delete then you can remove the @CacheEvict annotation to update and delete methods.

 

 

How much difference can we expect after ehcache successful implementation ?

I tried to load 1885 records without ehcache it takes around 7 to 13 seconds.

After implementing the ehcace successfully it takes less than a minute (even around 300ms only) to load same number of records from second time to live seconds alive (which we configured in the ehcache.xml file).

 

Overall, this is simple awesome!

 

Hope it helps someone!

Leave a Reply