1. Add pom dependencies
dependency groupIdorg.springframework</groupId artifactIdspring-context-support</artifactId </dependency> dependency> groupIdnet.sf.ehcache</groupId artifactIdehcache</artifactId version2.8.3</version </dependency
2. Configure ehcahe.xml file
<?xml version="1.0" encoding="UTF-8"?> ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ ehcache.xsd" updateCheckmaxElementsInMemory=" 1000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" /> cache name="demo" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" /> </ehcache3. Add configuration class:
@Configuration @EnableCaching public class EhCacheConfiguration { /* * ehcache main manager */ @Bean public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){ return new EhCacheCacheManager (bean. getObject ()); } /* * According to the setting of shared or not, Spring creates an ehcache base through CacheManager.create() or new CacheManager() respectively. */ @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){ EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean (); cacheManagerFactoryBean.setConfigLocation (new ClassPathResource("cache/ehcache.xml" )); cacheManagerFactoryBean.setShared (true); return cacheManagerFactoryBean; } }
4. Use
@Cacheable
@CachePut
@Service public class CacheService { @Cacheable(value = "demo",key="#methodName+#argus") public Object getResult(String methodName,String argus,ProceedingJoinPoint thisJoinPoint){ try { System.out.printf(" Method Execution..."); Object result = thisJoinPoint. proceed(); return result; } catch (Throwable throwable) { throwable. printStackTrace(); } return null; } }
color:#000080″>public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
return new EhCacheCacheManager (bean. getObject ());
}/*
* According to the setting of shared or not, Spring creates an ehcache base through CacheManager.create() or new CacheManager() respectively.
*/
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean ();
cacheManagerFactoryBean.setConfigLocation (new ClassPathResource(“cache/ehcache.xml” ));
cacheManagerFactoryBean.setShared (true);
return cacheManagerFactoryBean;
}
}
4. Use
@Cacheable
@CachePut
@Service public class CacheService { @Cacheable(value = "demo",key="#methodName+#argus") public Object getResult(String methodName,String argus,ProceedingJoinPoint thisJoinPoint){ try { System.out.printf(" Method Execution..."); Object result = thisJoinPoint. proceed(); return result; } catch (Throwable throwable) { throwable. printStackTrace(); } return null; } }