Spring Boot2 系列教程Spring Boot 整合 Ehcache
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import org.springframework.cache.CacheManager;
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 org.springframework.core.io.ClassPathResource;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
cacheManagerFactoryBean.setShared(true);
return cacheManagerFactoryBean;
}
@Bean
public Cache sampleCache() {
return new Cache(new CacheConfiguration("sampleCache", 5000).eternal(true).overflowToDisk(false));
}
}
这个配置类定义了如何在Spring Boot应用程序中整合Ehcache。首先,它配置了一个CacheManager
,这是Spring的缓存管理器,它委托Ehcache进行实际的缓存操作。然后,它定义了一个EhCacheManagerFactoryBean
,这是Spring用来创建Ehcache的CacheManager的。最后,它定义了一个名为"sampleCache"的Ehcache缓存配置。
评论已关闭