springmvc和encache集成关键代码和总结

简介: springmvc和encache集成关键代码和总结

基于注解的spring缓存配置 了解更多与spring集成的Echache  还有分布式的mencache让我更好学习了oscache

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

/**
 * ehcache-spring-annotations简介
 * @see ----------------------------------------------------------------------------------------------------------------
 * @see 关于Spring与Ehcache的集成,googlecode上有一个经Apache认证的开源项目叫做ehcache-spring-annotations
 * @see 目前已经到了1.2.0版本,它只是简化了Spring和Ehcache集成的复杂性(事实上我觉得完全没必要,因为它俩集成并不复杂)
 * @see 尽管如此还是要提一下,它的项目主页为https://code.google.com/p/ehcache-spring-annotations/
 * @see 这篇文章中描述了其用法http://blog.goyello.com/2010/07/29/quick-start-with-ehcache-annotations-for-spring/
 * @see ----------------------------------------------------------------------------------------------------------------
 * @see 1)使用时在项目中引入ehcache-spring-annotations-1.2.0.jar和guava-r09.jar两个jar文件
 * @see 2)然后在applicationContext.xml按照如下配置
 * @see   <beans xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
 * @see     xsi:schemaLocation="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
 * @see     http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.2.xsd">
 * @see   <ehcache:annotation-driven/>
 * @see   <ehcache:config cache-manager="cacheManager">
 * @see     <ehcache:evict-expired-elements interval="60"/>
 * @see   </ehcache:config>
 * @see   <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
 * @see     <property name="configLocation" value="classpath:ehcache.xml"/>
 * @see   </bean>
 * @see 3)最后在需要缓存的方法上使用@Cacheable和@TriggersRemove注解即可
 * @see   经我亲测,@TriggersRemove(cacheName="..", when="..", removeAll=true)可移除缓存中的全部对象
 * @see   但若写成@TriggersRemove(cacheName="..", when="..")则不会移除缓存中的单一的或所有的对象,即缓存中的对象无变化
 * @see ----------------------------------------------------------------------------------------------------------------
 * @create Oct 3, 2013 4:56:35 PM
 * @author 玄玉<http://blog.csdn.net/jadyer>
 */

然后是//src//applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
  xmlns:cache="http://www.springframework.org/schema/cache"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.2.xsd">
  <context:component-scan base-package="com.jadyer"/>
  <!-- SpringMVC配置 -->
  <mvc:annotation-driven/>
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
  <mvc:view-controller path="/" view-name="forward:/index.jsp"/>
  <!-- 缓存配置 -->
  <!-- 启用缓存注解功能(请将其配置在Spring主配置文件中) -->
  <cache:annotation-driven cache-manager="cacheManager"/>
  <!-- Spring自己的基于java.util.concurrent.ConcurrentHashMap实现的缓存管理器(该功能是从Spring3.1开始提供的) -->
  <!-- 
  <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
    <property name="caches">
      <set>
        <bean name="myCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"/>
      </set>
    </property>
  </bean>
   -->
  <!-- 若只想使用Spring自身提供的缓存器,则注释掉下面的两个关于Ehcache配置的bean,并启用上面的SimpleCacheManager即可 -->
  <!-- Spring提供的基于的Ehcache实现的缓存管理器 -->
  <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml"/>
  </bean>
  <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="cacheManagerFactory"/>
  </bean>
</beans>



下面是//src//ehcache.xml

<!-- Ehcache2.x的变化(取自https://github.com/springside/springside4/wiki/Ehcache) -->
<!-- 1)最好在ehcache.xml中声明不进行updateCheck -->
<!-- 2)为了配合BigMemory和Size Limit,原来的属性最好改名 -->
<!--   maxElementsInMemory->maxEntriesLocalHeap -->
<!--   maxElementsOnDisk->maxEntriesLocalDisk -->
<ehcache>
  <diskStore path="java.io.tmpdir"/>
  <defaultCache
       maxElementsInMemory="1000"
       eternal="false"
       timeToIdleSeconds="120"
       timeToLiveSeconds="120"
       overflowToDisk="false"/>
  <cache name="myCache"
       maxElementsOnDisk="20000"
       maxElementsInMemory="2000"
       eternal="true"
       overflowToDisk="true"
       diskPersistent="true"/>
</ehcache>
<!--
<diskStore>==========当内存缓存中对象数量超过maxElementsInMemory时,将缓存对象写到磁盘缓存中(需对象实现序列化接口)
<diskStore path="">==用来配置磁盘缓存使用的物理路径,Ehcache磁盘缓存使用的文件后缀名是*.data和*.index
name=================缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)
maxElementsOnDisk====磁盘缓存中最多可以存放的元素数量,0表示无穷大
maxElementsInMemory==内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况
                     1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中
                     2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素
eternal==============缓存中对象是否永久有效,即是否永驻内存,true时将忽略timeToIdleSeconds和timeToLiveSeconds
timeToIdleSeconds====缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,此为可选属性
                     即访问这个cache中元素的最大间隔时间,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除
timeToLiveSeconds====缓存数据在失效前的允许存活时间(单位:秒),仅当eternal=false时使用,默认值是0表示可存活时间无穷大
                     即Cache中的某元素从创建到清楚的生存时间,也就是说从创建开始计时,当超过这个时间时,此元素将从Cache中清除
overflowToDisk=======内存不足时,是否启用磁盘缓存(即内存中对象数量达到maxElementsInMemory时,Ehcache会将对象写到磁盘中)
                     会根据标签中path值查找对应的属性值,写入磁盘的文件会放在path文件夹下,文件的名称是cache的名称,后缀名是data
diskPersistent=======是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件
                     这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存
                     要想把cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法
diskExpiryThreadIntervalSeconds==磁盘缓存的清理线程运行间隔,默认是120秒
diskSpoolBufferSizeMB============设置DiskStore(磁盘缓存)的缓存区大小,默认是30MB
memoryStoreEvictionPolicy========内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存
                                 共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)
-->

下面是需要被缓存处理的UserService.java

package com.jadyer.service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
 * Cacheable注解负责将方法的返回值加入到缓存中
 * CacheEvict注解负责清除缓存(它的三个参数与@Cacheable的意思是一样的)
 * @see ----------------------------------------------------------------------------------------------------------
 * @see value------缓存位置的名称,不能为空,若使用EHCache则其值为ehcache.xml中的<cache name="myCache"/>
 * @see key--------缓存的Key,默认为空(表示使用方法的参数类型及参数值作为key),支持SpEL
 * @see condition--只有满足条件的情况才会加入缓存,默认为空(表示全部都加入缓存),支持SpEL
 * @see ----------------------------------------------------------------------------------------------------------
 * @see 该注解的源码位于spring-context-3.2.4.RELEASE-sources.jar中
 * @see Spring针对Ehcache支持的Java源码位于spring-context-support-3.2.4.RELEASE-sources.jar中
 * @see ----------------------------------------------------------------------------------------------------------
 * @create Oct 3, 2013 6:17:54 PM
 * @author 玄玉<http://blog.csdn.net/jadyer>
 */
@Service
public class UserService {
  private Map<String, String> usersData = new ConcurrentHashMap<String, String>();
  public UserService(){
    System.out.println("用户数据初始化..开始");
    usersData.put("2", "玄玉");
    usersData.put("3", "我的博客:http://blog.csdn.net/jadyer");
    System.out.println("用户数据初始化..完毕");
  }
  //将查询到的数据缓存到myCache中,并使用方法名称加上参数中的userNo作为缓存的key
  //通常更新操作只需刷新缓存中的某个值,所以为了准确的清除特定的缓存,故定义了这个唯一的key,从而不会影响其它缓存值
  @Cacheable(value="myCache", key="'get'+#userNo")
  public String get(String userNo){
    System.out.println("数据库中查到此用户号[" + userNo + "]对应的用户名为[" + usersData.get(userNo) + "]");
    return usersData.get(userNo);
  }
  @CacheEvict(value="myCache", key="'get'+#userNo")
  public void update(String userNo){
    System.out.println("移除缓存中此用户号[" + userNo + "]对应的用户名[" + usersData.get(userNo) + "]的缓存");
  }
  //allEntries为true表示清除value中的全部缓存,默认为false
  @CacheEvict(value="myCache", allEntries=true)
  public void removeAll(){
    System.out.println("移除缓存中的所有数据");
  }
}
package com.jadyer.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.jadyer.service.UserService;
/**
 * 这里用到的jar如下
 * aopalliance.jar
 * commons-logging-1.1.2.jar
 * ehcache-2.7.4.jar
 * slf4j-api-1.7.5.jar
 * spring-aop-3.2.4.RELEASE.jar
 * spring-beans-3.2.4.RELEASE.jar
 * spring-context-3.2.4.RELEASE.jar
 * spring-context-support-3.2.4.RELEASE.jar
 * spring-core-3.2.4.RELEASE.jar
 * spring-expression-3.2.4.RELEASE.jar
 * spring-web-3.2.4.RELEASE.jar
 * spring-webmvc-3.2.4.RELEASE.jar
 * @create Oct 3, 2013 6:22:43 PM
 * @author 玄玉<http://blog.csdn.net/jadyer>
 */
@Controller
@RequestMapping("cacheTest")
public class UserController {
  @Resource
  private UserService userService;
  @RequestMapping(value="/get/{userNo}", method=RequestMethod.GET)
  public String get(@PathVariable String userNo, Model model){
    String username = userService.get(userNo);
    model.addAttribute("username", username);
    return "getUser";
  }
  @RequestMapping(value="/update/{userNo}", method=RequestMethod.GET)
  public String update(@PathVariable String userNo, Model model){
    userService.update(userNo);
    model.addAttribute("userNo", userNo);
    return "updateUser";
  }
  @RequestMapping(value="/removeAll", method=RequestMethod.GET)
  public String removeAll(){
    userService.removeAll();
    return "removeAllUser";
  }
}

是UserController.java

最后把剩下的4个jsp页面列出来,首先是index.jsp



<%@ page language="java" pageEncoding="UTF-8"%>

查看<a href="<%=request.getContextPath()%>/cacheTest/get/2" target="_blank">2号</a>用户名

<br/>

<br/>

查看<a href="<%=request.getContextPath()%>/cacheTest/get/3" target="_blank">3号</a>用户名

<br/>

<br/>

更新<a href="<%=request.getContextPath()%>/cacheTest/update/3" target="_blank">3号</a>用户名

<br/>

<br/>

移除<a href="<%=request.getContextPath()%>/cacheTest/removeAll" target="_blank">所有</a>用户名

下面是getUser.jsp



<%@ page language="java" pageEncoding="UTF-8"%>

当前用户名为${username}


下面是updateUser.jsp




<%@ page language="java" pageEncoding="UTF-8"%>

已更新${userNo}号用户

最后是removeAllUser.jsp


<%@ page language="java" pageEncoding="UTF-8"%>

已移除所有用户




spring.xml里面的文件配置



xmlns:cache="http://www.springframework.org/schema/cache" 
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
<!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
<cache:annotation-driven cache-manager="cacheManager" />
<!-- spring自己的换管理器,这里定义了两个缓存位置名称 ,既注解中的value -->
<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="config" />
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="folder" />
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="acticle" />
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="attachment" />
</set>
</property>
</bean>







测试时,访问index.jsp之后点击各个链接并依次观察控制台输出即可

缓存有效果的特征是:第二次查询数据时不会访问数据库(即不打印日志)


相关文章
SpringMVC入门到实战------5、域对象共享数据 Request、Session、Application、Model、ModelAndView、Map、ModelMap的详细使用及代码实例
这篇文章详细解释了在IntelliJ IDEA中如何使用Mute Breakpoints功能来快速跳过程序中的后续断点,并展示了如何一键清空所有设置的断点。
SpringMVC入门到实战------5、域对象共享数据 Request、Session、Application、Model、ModelAndView、Map、ModelMap的详细使用及代码实例
|
1月前
|
XML JSON 数据库
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)
这篇文章详细介绍了RESTful的概念、实现方式,以及如何在SpringMVC中使用HiddenHttpMethodFilter来处理PUT和DELETE请求,并通过具体代码案例分析了RESTful的使用。
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)
|
22天前
|
Java Devops 持续交付
探索Java中的Lambda表达式:简化代码,提升效率DevOps实践:持续集成与部署的自动化之路
【8月更文挑战第30天】本文深入探讨了Java 8中引入的Lambda表达式如何改变了我们编写和管理代码的方式。通过简化代码结构,提高开发效率,Lambda表达式已成为现代Java开发不可或缺的一部分。文章将通过实际例子展示Lambda表达式的强大功能和优雅用法。
|
23天前
|
监控 前端开发 JavaScript
ARMS集成监控代码
【8月更文挑战第24天】
36 6
|
22天前
|
jenkins 持续交付 网络安全
利用 Jenkins 实现持续集成与持续部署-代码拉取终端的配置
【8月更文挑战第30天】在Jenkins服务器中,git和Gitee是常用的代码拉取终端。Git作为分布式版本控制系统,具备出色的灵活性和可扩展性;而Gitee则在国内网络环境下表现更佳,适合团队协作。Git配置包括安装、设置用户信息及生成SSH密钥等步骤;Gitee配置也类似,需注册账号、创建仓库、配置基本信息并设置远程仓库地址。开发人员提交代码后,可通过Webhook、定时轮询或事件监听等方式触发Jenkins动作,确保持续集成和部署高效运行。正确配置这些触发机制并通过测试验证其有效性至关重要。
44 2
SpringMVC入门到实战------3、@RequestMapping注解(超详细基础知识+实际代码案例)
该博客文章详细介绍了SpringMVC中`@RequestMapping`注解的使用方法,包括其功能、位置、value属性、method属性、params属性、headers属性以及支持的路径风格和占位符,并通过实际代码案例展示了如何建立请求与控制器方法之间的映射关系。
SpringMVC入门到实战------3、@RequestMapping注解(超详细基础知识+实际代码案例)
|
18天前
|
jenkins 持续交付 网络安全
利用 Jenkins 实现持续集成与持续部署-代码拉取终端的配置
安装Git、配置用户信息、生成SSH密钥以及在Gitee上创建项目仓库等。
43 0
|
1月前
|
jenkins Java 持续交付
【一键搞定!】Jenkins 自动发布 Java 代码的神奇之旅 —— 从零到英雄的持续集成/部署实战秘籍!
【8月更文挑战第9天】随着软件开发自动化的发展,持续集成(CI)与持续部署(CD)已成为现代流程的核心。Jenkins 作为一款灵活且功能丰富的开源 CI/CD 工具,在业界应用广泛。以一家电商公司的 Java 后端服务为例,通过搭建 Jenkins 自动化发布流程,包括创建 Jenkins 项目、配置 Git 仓库、设置构建触发器以及编写构建脚本等步骤,可以实现代码的快速可靠部署。
52 2
|
20天前
|
C# Windows 开发者
当WPF遇见OpenGL:一场关于如何在Windows Presentation Foundation中融入高性能跨平台图形处理技术的精彩碰撞——详解集成步骤与实战代码示例
【8月更文挑战第31天】本文详细介绍了如何在Windows Presentation Foundation (WPF) 中集成OpenGL,以实现高性能的跨平台图形处理。通过具体示例代码,展示了使用SharpGL库在WPF应用中创建并渲染OpenGL图形的过程,包括开发环境搭建、OpenGL渲染窗口创建及控件集成等关键步骤,帮助开发者更好地理解和应用OpenGL技术。
68 0
|
20天前
|
开发者 C# UED
WPF与多媒体:解锁音频视频播放新姿势——从界面设计到代码实践,全方位教你如何在WPF应用中集成流畅的多媒体功能
【8月更文挑战第31天】本文以随笔形式介绍了如何在WPF应用中集成音频和视频播放功能。通过使用MediaElement控件,开发者能轻松创建多媒体应用程序。文章详细展示了从创建WPF项目到设计UI及实现媒体控制逻辑的过程,并提供了完整的示例代码。此外,还介绍了如何添加进度条等额外功能以增强用户体验。希望本文能为WPF开发者提供实用的技术指导与灵感。
42 0