Tuesday, March 3, 2020

To configure EhCache to Spring Boot Application

To configure EhCache to Spring Boot Application

First we have to add the following maven dependency to Application (Note versions will be taken care by spring boot starter (which we have added initial setup))
		
                
			org.springframework.boot
			spring-boot-starter-cache
		

		
			javax.cache
			cache-api
		

		
			org.ehcache
			ehcache
		

Add the following class to application as setup
	package com.nagarajuconfig;

import java.util.concurrent.TimeUnit;

import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.spi.CachingProvider;

import org.springframework.stereotype.Component;

@Component
public class CacheSetup {

	public CacheManager cacheManager() {
		CachingProvider provider = Caching.getCachingProvider();
		CacheManager cacheManager = provider.getCacheManager();

		cacheManager.createCache("cacheName", getCacheConfiguration());

		return cacheManager;
	}

	private MutableConfiguration getCacheConfiguration() {
		return new MutableConfiguration().setTypes(Object.class, Object.class).setStoreByValue(false)
				.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MINUTES, 1)))
				.setStatisticsEnabled(true);
	}

}

Add the following to service layer or dao layer ..I have added in the service Layer.
	@Override
	/* @Cacheable(cacheNames = "controllerParamData",key="#controllerId") */
	@CacheResult(cacheName = "controllerParamData")
	public List getParamData(Long controllerId, String type, String sort, Integer count,
			Long startTime, Long endTime, List paramKey)
Now enable the Cache
	package com.nagaraju.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 
 */
@Configuration
@EnableCaching
public class CacheConfiguration {

	@Autowired
	private CacheSetup cacheSetup;
	
	@Bean
	JCacheCacheManager jCacheCacheManager() {
		return new JCacheCacheManager(cacheSetup.cacheManager());
	}

}

Run application, then will setup the cache automatically.

No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...