java启动项目添加ehcache缓存

1.web.xml配置监听器

<listener>  
    <listener-class>  
        cn.com.highset.goexpo.util.CacheListener
    </listener-class>  
</listener>

2.重写ContextLoaderListener的contextInitialized方法

public class CacheListener extends ContextLoaderListener{
	
    @Override  
    public void contextInitialized(ServletContextEvent event) {  
        super.contextInitialized(event);  
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());          
        //获取bean  
        IBaseDao baseDao = (IBaseDao) applicationContext.getBean("baseDao");  
        CacheManager cacheManager = (CacheManager) applicationContext.getBean("cacheManager");  
        Cache cache = cacheManager.getCache("cachePool"); 
        cache.put("key", "value");
    }
}

3.配置ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <diskStore path="java.io.tmpdir" />
    <defaultCache maxElementsInMemory="500" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="1200"  overflowToDisk="true" />
    <cache name="cachePool" maxElementsInMemory="150" eternal="true" timeToLiveSeconds="0"  timeToIdleSeconds="0" overflowToDisk="false" />
</ehcache>

4.配置spring缓存管理器

<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
    <property name="configLocation" value="/WEB-INF/applicationContext-ehcache.xml" />  
</bean>  
      
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">      
    <property name="cacheManager"  ref="cacheManagerFactory"/>      
</bean>

5.通过注解注入org.springframework.cache.CacheManager

@Autowired
private CacheManager cacheManager;

6.查询cache缓存

Cache cache = cacheManager.getCache("cachePool");
Object value = cache.get("key").get();

猜你喜欢

转载自blog.csdn.net/rexueqingchun/article/details/80169605