SpringMVC整合Ehcache

这里用的是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之后点击各个链接并依次观察控制台输出即可
缓存有效果的特征是:第二次查询数据时不会访问数据库(即不打印日志)

 

猜你喜欢

转载自himo-zhang.iteye.com/blog/2198450