SpringBoot系列:Spring Boot集成Spring Cache,使用EhCache
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import net.sf.ehcache.CacheManager;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public EhCacheManagerFactoryBean cacheManagerFactoryBean() {
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
cacheManagerFactoryBean.setShared(true);
return cacheManagerFactoryBean;
}
@Bean
public CacheManager cacheManager() {
return cacheManagerFactoryBean().getObject();
}
@Bean
public EhCacheCacheManager ehCacheCacheManager() {
return new EhCacheCacheManager(cacheManager());
}
}
这段代码定义了一个配置类,它使用Spring Cache和EhCache来创建缓存管理器。它首先定义了一个EhCacheManagerFactoryBean
,这是Spring用来创建EhCache的CacheManager的。然后,它通过cacheManager()
方法返回了CacheManager的实例,并最终创建了一个EhCacheCacheManager
的Bean,这个Bean可以被Spring Cache抽象层用来管理缓存。
评论已关闭