Spring自定義緩存管理及配置Ehcache緩存

Spring自帶緩存、自建緩存管理器等都可解決項目部分性能問題。結合Ehcache後性能更優,使用也比較簡單。

在進行Ehcache學習之前,最好對Spring自帶的緩存管理有一個總體的認識。

這篇文章不錯:https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/

這裏用的是SpringMVC-3.2.4和Ehcache-2.7.4

介紹二者集成之前,先介紹下GoogleCode上的ehcache-spring-annotations項目

  1. /** 
  2.  * ehcache-spring-annotations簡介 
  3.  * @see ---------------------------------------------------------------------------------------------------------------- 
  4.  * @see 關於Spring與Ehcache的集成,googlecode上有一個經Apache認證的開源項目叫做ehcache-spring-annotations 
  5.  * @see 目前已經到了1.2.0版本,它只是簡化了Spring和Ehcache集成的複雜性(事實上我覺得完全沒必要,因爲它倆集成並不複雜) 
  6.  * @see 儘管如此還是要提一下,它的項目主頁爲https://code.google.com/p/ehcache-spring-annotations/ 
  7.  * @see 這篇文章中描述了其用法http://blog.goyello.com/2010/07/29/quick-start-with-ehcache-annotations-for-spring/ 
  8.  * @see ---------------------------------------------------------------------------------------------------------------- 
  9.  * @see 1)使用時在項目中引入ehcache-spring-annotations-1.2.0.jar和guava-r09.jar兩個jar文件 
  10.  * @see 2)然後在applicationContext.xml按照如下配置 
  11.  * @see   <beans xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring" 
  12.  * @see         xsi:schemaLocation="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring 
  13.  * @see         http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.2.xsd"> 
  14.  * @see   <ehcache:annotation-driven/> 
  15.  * @see   <ehcache:config cache-manager="cacheManager"> 
  16.  * @see       <ehcache:evict-expired-elements interval="60"/> 
  17.  * @see   </ehcache:config> 
  18.  * @see   <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
  19.  * @see       <property name="configLocation" value="classpath:ehcache.xml"/> 
  20.  * @see   </bean> 
  21.  * @see 3)最後在需要緩存的方法上使用@Cacheable和@TriggersRemove註解即可 
  22.  * @see   經我親測,@TriggersRemove(cacheName="..", when="..", removeAll=true)可移除緩存中的全部對象 
  23.  * @see   但若寫成@TriggersRemove(cacheName="..", when="..")則不會移除緩存中的單一的或所有的對象,即緩存中的對象無變化 
  24.  * @see ---------------------------------------------------------------------------------------------------------------- 
  25.  * @create Oct 3, 2013 4:56:35 PM 
  26.  * @author 玄玉<http://blog.csdn.net/jadyer> 
  27.  */  
下面開始羅列示例代碼,首先是web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.     <!-- SpringMVC核心分發器 -->  
  8.     <servlet>  
  9.         <servlet-name>SpringMVC</servlet-name>  
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  11.         <init-param>  
  12.             <param-name>contextConfigLocation</param-name>  
  13.             <param-value>classpath:applicationContext.xml</param-value>  
  14.         </init-param>  
  15.         <load-on-startup>1</load-on-startup>  
  16.     </servlet>  
  17.     <servlet-mapping>  
  18.         <servlet-name>SpringMVC</servlet-name>  
  19.         <url-pattern>/</url-pattern>  
  20.     </servlet-mapping>  
  21. </web-app>  
然後是//src//applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  5.     xmlns:cache="http://www.springframework.org/schema/cache"  
  6.     xmlns:context="http://www.springframework.org/schema/context"  
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.                         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  9.                         http://www.springframework.org/schema/mvc  
  10.                         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
  11.                         http://www.springframework.org/schema/cache  
  12.                         http://www.springframework.org/schema/cache/spring-cache-3.2.xsd  
  13.                         http://www.springframework.org/schema/context  
  14.                         http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
  15.     <context:component-scan base-package="com.jadyer"/>  
  16.       
  17.     <!-- SpringMVC配置 -->  
  18.     <mvc:annotation-driven/>  
  19.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  20.         <property name="prefix" value="/"/>  
  21.         <property name="suffix" value=".jsp"/>  
  22.     </bean>  
  23.     <mvc:view-controller path="/" view-name="forward:/index.jsp"/>  
  24.       
  25.     <!-- 緩存配置 -->  
  26.     <!-- 啓用緩存註解功能(請將其配置在Spring主配置文件中) -->  
  27.     <cache:annotation-driven cache-manager="cacheManager"/>  
  28.     <!-- Spring自己的基於java.util.concurrent.ConcurrentHashMap實現的緩存管理器(該功能是從Spring3.1開始提供的) -->  
  29.     <!--   
  30.     <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">  
  31.         <property name="caches">  
  32.             <set>  
  33.                 <bean name="myCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"/>  
  34.             </set>  
  35.         </property>  
  36.     </bean>  
  37.      -->  
  38.     <!-- 若只想使用Spring自身提供的緩存器,則註釋掉下面的兩個關於Ehcache配置的bean,並啓用上面的SimpleCacheManager即可 -->  
  39.     <!-- Spring提供的基於的Ehcache實現的緩存管理器 -->  
  40.     <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
  41.         <property name="configLocation" value="classpath:ehcache.xml"/>  
  42.     </bean>  
  43.     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">  
  44.         <property name="cacheManager" ref="cacheManagerFactory"/>  
  45.     </bean>  
  46. </beans>  
下面是//src//ehcache.xml

  1. <!-- Ehcache2.x的變化(取自https://github.com/springside/springside4/wiki/Ehcache) -->  
  2. <!-- 1)最好在ehcache.xml中聲明不進行updateCheck -->  
  3. <!-- 2)爲了配合BigMemory和Size Limit,原來的屬性最好改名 -->  
  4. <!--   maxElementsInMemory->maxEntriesLocalHeap -->  
  5. <!--   maxElementsOnDisk->maxEntriesLocalDisk -->  
  6. <ehcache>  
  7.     <diskStore path="java.io.tmpdir"/>  
  8.     <defaultCache  
  9.            maxElementsInMemory="1000"  
  10.            eternal="false"  
  11.            timeToIdleSeconds="120"  
  12.            timeToLiveSeconds="120"  
  13.            overflowToDisk="false"/>  
  14.     <cache name="myCache"  
  15.            maxElementsOnDisk="20000"  
  16.            maxElementsInMemory="2000"  
  17.            eternal="true"  
  18.            overflowToDisk="true"  
  19.            diskPersistent="true"/>  
  20. </ehcache>  
  21. <!--  
  22. <diskStore>==========當內存緩存中對象數量超過maxElementsInMemory時,將緩存對象寫到磁盤緩存中(需對象實現序列化接口)  
  23. <diskStore path="">==用來配置磁盤緩存使用的物理路徑,Ehcache磁盤緩存使用的文件後綴名是*.data和*.index  
  24. name=================緩存名稱,cache的唯一標識(ehcache會把這個cache放到HashMap裏)  
  25. maxElementsOnDisk====磁盤緩存中最多可以存放的元素數量,0表示無窮大  
  26. maxElementsInMemory==內存緩存中最多可以存放的元素數量,若放入Cache中的元素超過這個數值,則有以下兩種情況  
  27.                      1)若overflowToDisk=true,則會將Cache中多出的元素放入磁盤文件中  
  28.                      2)若overflowToDisk=false,則根據memoryStoreEvictionPolicy策略替換Cache中原有的元素  
  29. eternal==============緩存中對象是否永久有效,即是否永駐內存,true時將忽略timeToIdleSeconds和timeToLiveSeconds  
  30. timeToIdleSeconds====緩存數據在失效前的允許閒置時間(單位:秒),僅當eternal=false時使用,默認值是0表示可閒置時間無窮大,此爲可選屬性  
  31.                      即訪問這個cache中元素的最大間隔時間,若超過這個時間沒有訪問此Cache中的某個元素,那麼此元素將被從Cache中清除  
  32. timeToLiveSeconds====緩存數據在失效前的允許存活時間(單位:秒),僅當eternal=false時使用,默認值是0表示可存活時間無窮大  
  33.                      即Cache中的某元素從創建到清楚的生存時間,也就是說從創建開始計時,當超過這個時間時,此元素將從Cache中清除  
  34. overflowToDisk=======內存不足時,是否啓用磁盤緩存(即內存中對象數量達到maxElementsInMemory時,Ehcache會將對象寫到磁盤中)  
  35.                      會根據標籤中path值查找對應的屬性值,寫入磁盤的文件會放在path文件夾下,文件的名稱是cache的名稱,後綴名是data  
  36. diskPersistent=======是否持久化磁盤緩存,當這個屬性的值爲true時,系統在初始化時會在磁盤中查找文件名爲cache名稱,後綴名爲index的文件  
  37.                      這個文件中存放了已經持久化在磁盤中的cache的index,找到後會把cache加載到內存  
  38.                      要想把cache真正持久化到磁盤,寫程序時注意執行net.sf.ehcache.Cache.put(Element element)後要調用flush()方法  
  39. diskExpiryThreadIntervalSeconds==磁盤緩存的清理線程運行間隔,默認是120秒  
  40. diskSpoolBufferSizeMB============設置DiskStore(磁盤緩存)的緩存區大小,默認是30MB  
  41. memoryStoreEvictionPolicy========內存存儲與釋放策略,即達到maxElementsInMemory限制時,Ehcache會根據指定策略清理內存  
  42.                                  共有三種策略,分別爲LRU(最近最少使用)、LFU(最常用的)、FIFO(先進先出)  
  43. -->  
下面是需要被緩存處理的UserService.java

  1. package com.jadyer.service;  
  2.   
  3. import java.util.Map;  
  4. import java.util.concurrent.ConcurrentHashMap;  
  5.   
  6. import org.springframework.cache.annotation.CacheEvict;  
  7. import org.springframework.cache.annotation.Cacheable;  
  8. import org.springframework.stereotype.Service;  
  9.   
  10. /** 
  11.  * Cacheable註解負責將方法的返回值加入到緩存中 
  12.  * CacheEvict註解負責清除緩存(它的三個參數與@Cacheable的意思是一樣的) 
  13.  * @see ---------------------------------------------------------------------------------------------------------- 
  14.  * @see value------緩存位置的名稱,不能爲空,若使用EHCache則其值爲ehcache.xml中的<cache name="myCache"/> 
  15.  * @see key--------緩存的Key,默認爲空(表示使用方法的參數類型及參數值作爲key),支持SpEL 
  16.  * @see condition--只有滿足條件的情況纔會加入緩存,默認爲空(表示全部都加入緩存),支持SpEL 
  17.  * @see ---------------------------------------------------------------------------------------------------------- 
  18.  * @see 該註解的源碼位於spring-context-3.2.4.RELEASE-sources.jar中 
  19.  * @see Spring針對Ehcache支持的Java源碼位於spring-context-support-3.2.4.RELEASE-sources.jar中 
  20.  * @see ---------------------------------------------------------------------------------------------------------- 
  21.  * @create Oct 3, 2013 6:17:54 PM 
  22.  * @author 玄玉<http://blog.csdn.net/jadyer> 
  23.  */  
  24. @Service  
  25. public class UserService {  
  26.     private Map<String, String> usersData = new ConcurrentHashMap<String, String>();  
  27.       
  28.     public UserService(){  
  29.         System.out.println("用戶數據初始化..開始");  
  30.         usersData.put("2""玄玉");  
  31.         usersData.put("3""我的博客:http://blog.csdn.net/jadyer");  
  32.         System.out.println("用戶數據初始化..完畢");  
  33.     }  
  34.       
  35.     //將查詢到的數據緩存到myCache中,並使用方法名稱加上參數中的userNo作爲緩存的key  
  36.     //通常更新操作只需刷新緩存中的某個值,所以爲了準確的清除特定的緩存,故定義了這個唯一的key,從而不會影響其它緩存值  
  37.     @Cacheable(value="myCache", key="'get'+#userNo")  
  38.     public String get(String userNo){  
  39.         System.out.println("數據庫中查到此用戶號[" + userNo + "]對應的用戶名爲[" + usersData.get(userNo) + "]");  
  40.         return usersData.get(userNo);  
  41.     }  
  42.       
  43.     @CacheEvict(value="myCache", key="'get'+#userNo")  
  44.     public void update(String userNo){  
  45.         System.out.println("移除緩存中此用戶號[" + userNo + "]對應的用戶名[" + usersData.get(userNo) + "]的緩存");  
  46.     }  
  47.       
  48.     //allEntries爲true表示清除value中的全部緩存,默認爲false  
  49.     @CacheEvict(value="myCache", allEntries=true)  
  50.     public void removeAll(){  
  51.         System.out.println("移除緩存中的所有數據");  
  52.     }  
  53. }  
下面是UserController.java

  1. package com.jadyer.controller;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.ui.Model;  
  7. import org.springframework.web.bind.annotation.PathVariable;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9. import org.springframework.web.bind.annotation.RequestMethod;  
  10.   
  11. import com.jadyer.service.UserService;  
  12.   
  13. /** 
  14.  * 這裏用到的jar如下 
  15.  * aopalliance.jar 
  16.  * commons-logging-1.1.2.jar 
  17.  * ehcache-2.7.4.jar 
  18.  * slf4j-api-1.7.5.jar 
  19.  * spring-aop-3.2.4.RELEASE.jar 
  20.  * spring-beans-3.2.4.RELEASE.jar 
  21.  * spring-context-3.2.4.RELEASE.jar 
  22.  * spring-context-support-3.2.4.RELEASE.jar 
  23.  * spring-core-3.2.4.RELEASE.jar 
  24.  * spring-expression-3.2.4.RELEASE.jar 
  25.  * spring-web-3.2.4.RELEASE.jar 
  26.  * spring-webmvc-3.2.4.RELEASE.jar 
  27.  * @create Oct 3, 2013 6:22:43 PM 
  28.  * @author 玄玉<http://blog.csdn.net/jadyer> 
  29.  */  
  30. @Controller  
  31. @RequestMapping("cacheTest")  
  32. public class UserController {  
  33.     @Resource  
  34.     private UserService userService;  
  35.       
  36.     @RequestMapping(value="/get/{userNo}", method=RequestMethod.GET)  
  37.     public String get(@PathVariable String userNo, Model model){  
  38.         String username = userService.get(userNo);  
  39.         model.addAttribute("username", username);  
  40.         return "getUser";  
  41.     }  
  42.       
  43.     @RequestMapping(value="/update/{userNo}", method=RequestMethod.GET)  
  44.     public String update(@PathVariable String userNo, Model model){  
  45.         userService.update(userNo);  
  46.         model.addAttribute("userNo", userNo);  
  47.         return "updateUser";  
  48.     }  
  49.       
  50.     @RequestMapping(value="/removeAll", method=RequestMethod.GET)  
  51.     public String removeAll(){  
  52.         userService.removeAll();  
  53.         return "removeAllUser";  
  54.     }  
  55. }  
最後把剩下的4個jsp頁面列出來,首先是index.jsp

  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. 查看<a href="<%=request.getContextPath()%>/cacheTest/get/2" target="_blank">2號</a>用戶名  
  3. <br/>  
  4. <br/>  
  5. 查看<a href="<%=request.getContextPath()%>/cacheTest/get/3" target="_blank">3號</a>用戶名  
  6. <br/>  
  7. <br/>  
  8. 更新<a href="<%=request.getContextPath()%>/cacheTest/update/3" target="_blank">3號</a>用戶名  
  9. <br/>  
  10. <br/>  
  11. 移除<a href="<%=request.getContextPath()%>/cacheTest/removeAll" target="_blank">所有</a>用戶名  
下面是getUser.jsp

  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. 當前用戶名爲${username}  
下面是updateUser.jsp

  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. 已更新${userNo}號用戶  
最後是removeAllUser.jsp

  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. 已移除所有用戶  

測試時,訪問index.jsp之後點擊各個鏈接並依次觀察控制檯輸出即可
緩存有效果的特徵是:第二次查詢數據時不會訪問數據庫(即不打印日誌)

發佈了79 篇原創文章 · 獲贊 12 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章