您的位置:首页 > 编程语言 > Java开发

EHcache注解使用(ehcache-spring-annotations)

2015-12-25 14:33 459 查看
第一步在web.xml中配置加载配置ehcache的配置文件,如

<context-param>  
     <param-name>contextConfigLocation</param-name>  
     <param-value>classpath:config/applicationContext.xml,classpath:config/ehcacheApplication.xml</param-value>  
 </context-param> 
第二部:编写ehcacheApplication.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">                                        
    <ehcache:annotation-driven />  
      
    <ehcache:config cache-manager="cacheManager">  

    </ehcache:config>  
      
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation"  value="classpath:config/ehcache.xml"/>  
    </bean>

  《!--缓存的生成key--》
    <bean id="productKeyGenerator" class="lwz.web.ehcache.ProductCacheKeyGenerator"/>    
      
</beans>  

第三部:ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>  
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">  
      
    <diskStore path="user.home/web_ehcache/" />   
      
    <defaultCache  
            maxElementsInMemory="3000"  
            eternal="false"  
            timeToIdleSeconds="3600"  
            timeToLiveSeconds="3600"  
            overflowToDisk="true"  
            diskPersistent="false"  
            diskExpiryThreadIntervalSeconds="100"  
            memoryStoreEvictionPolicy="LRU"  
            />  
    <cache name="testCache"  
           maxElementsInMemory="3000"  
           eternal="false"  
           overflowToDisk="true"  
           timeToIdleSeconds="36000"  
           timeToLiveSeconds="36000"  
           memoryStoreEvictionPolicy="LFU"  
            />  
</ehcache>   

第四部

然偶在dao的接口,或者类方法上加上@cacheable注解

@Cacheable(cacheName = "testCache")
public List<ApplicationMenu> findAllMenuValid(String flag);

记得最好不要在control类中的方法加上@Cacheable(cacheName = "testCache"),然后在方法内再去调用dao中的方法,这样缓存不到
如果要更新缓存 在方法上注释

@TriggersRemove(cacheName="testCache",removeAll=true) 
public void deleteMenu(int id);

即删除缓存
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息