1、配置类
@Configuration @EnableCaching public class CacheConfiguration {// implements CachingConfigurer { @Bean //@Override public CacheManager cacheManager() { EhCacheCacheManager cacheManager = new EhCacheCacheManager(); cacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject()); return cacheManager; } @Bean //@Override public KeyGenerator keyGenerator() { return new SimpleKeyGenerator(); } @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() { EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml")); ehCacheManagerFactoryBean.setCacheManagerName("messageCache"); ehCacheManagerFactoryBean.setShared(true); return ehCacheManagerFactoryBean; } // @Override // public CacheResolver cacheResolver() { // // TODO Auto-generated method stub // return new SimpleCacheResolver(); // } // // @Override // public CacheErrorHandler errorHandler() { // // TODO Auto-generated method stub // return new SimpleCacheErrorHandler(); // } }
2、位于resource目录下的配置文件ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" /> <cache name="messageCache" maxElementsInMemory="10" eternal="true" overflowToDisk="false" /> </ehcache>
3、Cache对象
@Cacheable(value="messageCache") public Integer testCashe( String data ) { return new Integer(data.length()); }
注意:Cache对象的value参数要与ehcache.xml配置文件中对应一致。