spring中緩存配置(完善)

1.引入依賴包
<dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.5.1</version>
    </dependency>

2.配置
以下配置是用spring自定義的一個簡單的緩存管理器
    <cache:annotation-driven/>

    <!-- generic cache manager --> 
   <bean id="cacheManager" 
   class="org.springframework.cache.support.SimpleCacheManager">
     <property name="caches"> 
       <set> 
         <bean 
           class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
           p:name="default" /> 
         <bean 
           class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
           p:name="nurseCache" /> 
       </set> 
     </property> 
   </bean>

可以用第三方的 如ehcache    ehcache.xml配置

<?xml version="1.0"?> 
<ehcache xmlms:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:noNamespaceSchemaLocation="ehcache.xsd"> 
    <diskStore path="cache" /> 
<!--     <defaultCache maxElementsInMemory="10000" eternal="false" --> 
<!--         timeToIdleSeconds="30" timeToLiveSeconds="30" overflowToDisk="false" /> --> 
    <cache name="nurseCache" maxElementsInMemory="10000" eternal="false" 
        timeToIdleSeconds="300" timeToLiveSeconds="10" overflowToDisk="false" 
        memoryStoreEvictionPolicy="LFU" /> 
    <cache name="bdHospitalCache" maxElementsInMemory="10000" eternal="false" 
        timeToIdleSeconds="300" timeToLiveSeconds="10" overflowToDisk="false" 
        memoryStoreEvictionPolicy="LFU" /> 
    <cache name="dicCache" maxElementsInMemory="10000" eternal="false" 
        timeToIdleSeconds="300" timeToLiveSeconds="360000" overflowToDisk="false" 
        memoryStoreEvictionPolicy="LFU" /> 
    <cache name="bannerCache" maxElementsInMemory="10000" eternal="false" 
        timeToIdleSeconds="300" timeToLiveSeconds="36000" overflowToDisk="false" 
        memoryStoreEvictionPolicy="LFU" /> 
    <cache name="dicItemCache" maxElementsInMemory="10000" eternal="false" 
        timeToIdleSeconds="300" timeToLiveSeconds="10" overflowToDisk="false" 
        memoryStoreEvictionPolicy="LFU" /> 
    <cache name="queryDicById" maxElementsInMemory="10000" eternal="false" 
        timeToIdleSeconds="300" timeToLiveSeconds="10" overflowToDisk="false" 
        memoryStoreEvictionPolicy="LFU" /> 
    <cache name="getCustomerInfo" maxElementsInMemory="10000" eternal="false" 
        timeToIdleSeconds="300" timeToLiveSeconds="10" overflowToDisk="false" 
        memoryStoreEvictionPolicy="LFU" /> 
</ehcache>
spring文件配置
<cache:annotation-driven cache-manager="ehcacheManager"/>
  <!-- cacheManager工廠類,指定ehcache.xml的位置 --> 
    <bean id="ehcacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
         <property name="configLocation" value="classpath:ehcache.xml" /> 
    </bean> 
    <!-- 聲明cacheManager --> 
    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> 
         <property name="cacheManager" ref="ehcacheManagerFactory" /> 
    </bean>


3.編碼
//存到緩存中的key值是查詢參數
    @Cacheable(value="nurseCache",key="#idItems")
    public List<Nurse> queryNurseListByIdCol(String idItems) {
        System.out.println("查詢數據庫");
        System.out.println(idItems);
        if(idItems == null || "".equals(idItems)){
            return null;
        }


        String url = apiQueryNursesByIds+"?idItems="+idItems;
        String result = HttpUtil.sendGet(url, "utf-8");
        System.out.println(result);
        HttpNurseListResult resultList = JSON.parseObject(result, HttpNurseListResult.class);
        if(resultList == null){
            return null;
        }
        int success = resultList.getSuccess();
        if(success != 1){
            return null;
        }

        return resultList.getData();
    }
多值組合key,比如下面例子代碼中的bannerDtoRpc對象中的city屬性與position屬性聯合組成key
    @Cacheable(value="bannerCache",key="#bannerDtoRpc.city.concat(T(String).valueOf(#bannerDtoRpc.position))") 
    public List<BannerRpc> queryCustomerBanners(BannerDtoRpc bannerDtoRpc) { 
        System.out.println("實際查詢"); 

        return bannerRpcDao.queryCustomerBanners(bannerDtoRpc); 
    }



4.管理緩存


在使用緩存時,如果我們對數據增,刪,改操作時,這個時候需要及時的清理相應key裏面的緩存,
在spring中可以直接用 @CacheEvict 註解,因爲我們的緩存並沒有獨立開來,例如用redis來管理緩存
這個時候對數據的增,刪,改可能在其他系統操作,則不能用這個註解,可以通過編碼的方式對外提供緩存
清理的接口

private CacheManager ehcacheManager; 

    @Override 
    public ResponseVoRpc clearCache(@Param("cacheName")String cacheName,@Param("request")HttpServletRequest request) { 
        ResponseVoRpc resp = new ResponseVoRpc(); 

         ServletContext servletContext = request.getServletContext();  
         WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);               
         ehcacheManager = (CacheManager)ctx.getBean("ehcacheManager" );  

        Cache cache = ehcacheManager.getCache(cacheName); 
        if(cache==null){ 
            resp.setCode(ResponseVoRpc.CODE_COMMON_SUCCESS); 
            resp.setCodeMsg(ResponseVoRpc.CODE_MAP.get(ResponseVoRpc.CODE_COMMON_SUCCESS)); 
            return resp; 
        } 
        cache.clear(); 
        resp.setCode(ResponseVoRpc.CODE_COMMON_SUCCESS); 
        resp.setCodeMsg(ResponseVoRpc.CODE_MAP.get(ResponseVoRpc.CODE_COMMON_SUCCESS)); 
        return resp; 
    }
注意:

5.redis管理緩存



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章