SpringMVC缓存管理及配置Ehcache缓存

本文介绍了如何在SpringMVC 3.2.4中集成Ehcache 2.7.4进行缓存管理。首先概述了Spring的缓存概念,然后详细展示了集成过程,包括web.xml配置、applicationContext.xml配置、ehcache.xml配置,以及UserService和UserServiceImpl的缓存注解使用。此外,还给出了index.jsp、updateUser.jsp和removeAllUser.jsp的页面逻辑,并通过项目部署图和测试步骤解释了缓存生效的判断标准——第二次查询数据时不访问数据库。
摘要由CSDN通过智能技术生成

在进行Ehcache学习之前,最好对Spring自带的缓存管理有一个总体的认识。

这里用的是SpringMVC-3.2.4和Ehcache-2.7.4


介绍二者集成之前,先介绍下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 ---------------------------------------------------------------------------------------------------------------- 
     * 
     * @author 李飞<http://blog.csdn.net/lifeifei2010/article/details/61921396> 
     */


下面开始罗列示例代码,首先是web.xml

两种模式自己根据框架选择:

第一种是资源文件包中采用classpath

<?xml version="1.0" encoding="UTF-8"?>  
    <web-app version="2.5"  
        xmlns="http://java.sun.com/xml/ns/javaee"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
        <!-- SpringMVC核心分发器 -->  
        <servlet>  
            <servlet-name>SpringMVC</servlet-name>  
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
            <init-param>  
                <param-name>contextConfigLocation</param-name>  
                <param-value>classpath:applicationContext.xml</param-value>  
            </init-param>  
            <load-on-startup>1</load-on-startup>  
        </servlet>  
        <servlet-mapping>  
            <servlet-name>SpringMVC</servlet-name>  
            <url-pattern>/</url-pattern>  
        </servlet-mapping>  
    </web-app>

第二种是资源文件包中采用路径

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets 
		and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

然后是//src//applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<context:component-scan base-package="com.rock.admin" />


	<!-- 缓存配置 -->
	<!-- 启用缓存注解功能 -->
	<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实现的缓存管理器 -->
	<beans:bean id="cacheManagerFactory"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<beans:property name="configLocation" value="classpath:spring/ehcache.xml" />
	</beans:bean>
	<beans:bean id="cacheManager"
		class="org.springframework.cache.ehcache.EhCacheCacheManager">
		<beans:property name="cacheManager" ref="cacheManagerFactory" />
	</beans:bean>

</beans:beans>


下面是//src//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="java.io.tmpdir/ehcache"/>

  <!-- 默认缓存 -->
  <defaultCache
          maxEntriesLocalHeap="10000"
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          maxEntriesLocalDisk="10000000"
          diskExpiryThreadIntervalSeconds="120"
          memoryStoreEvictionPolicy="LRU"/>
	<!--
	       配置自定义缓存
	       maxElementsInMemory:缓存中允许创建的最大对象数
	       eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
	       timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,
	                   两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,
	                   如果该值是 0 就意味着元素可以停顿无穷长的时间。
	       timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,
	                   这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
	       maxEntriesLocalDisk:磁盘缓存允许的最大对象数
	       overflowToDisk:内存不足时,是否启用磁盘缓存。
	       memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。
	   -->

  <!-- ehcaheOne缓存 -->
  <cache name="ehcaheOne"
         maxElementsInMemory="1000"
         eternal="true"
         timeToIdleSeconds="120"
         timeToLiveSeconds="120"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>
</ehcache>



下面是导入的ehcache jar包

<!-- ehcache -->
<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache</artifactId>
	<version>2.10.2</version>
	</dependency>
	<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context-support</artifactId>
	<version>4.1.4.RELEASE</version>
</dependency>




下面是UserController.java

package com.rock.admin.action;

import org.springframework.beans.factory.annotation.Autowired;
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.rock.admin.service.UserService;

/**
 * 
 * @author lifeifei
 * @version $Id: UserController.java, v 0.1 2017年3月13日 下午5:11:30 wb-lifeifei Exp $
 */
@Controller
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Object model) {
        return "index";
    }

    @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";
    }
}


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

package com.rock.admin.service;

/**
 * 用户管理接口
 * @author lifeifei
 * @version $Id: UserService.java, v 0.1 2017年3月13日 下午5:15:08 wb-lifeifei Exp $
 */
public interface UserService {
    public String get(String userNo);

    public void update(String userNo);

    public void removeAll();
}


下面是需要被缓存处理的实现类UserServiceImpl.java

package com.rock.admin.service.impl;

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;

import com.rock.admin.service.UserService;

/**
 * 用户管理实现类
 * @author lifeifei
 * @version $Id: UserServiceImpl.java, v 0.1 2017年3月13日 下午5:17:15 wb-lifeifei Exp $
 */
@Service
public class UserServiceImpl implements UserService {
    private Map<String, String> usersData = new ConcurrentHashMap<String, String>();

    public UserServiceImpl() {
        System.out.println("用户数据初始化..开始");
        usersData.put("1", "阿飞");
        usersData.put("2", "飞哥");
        usersData.put("3", "rock");
        System.out.println("用户数据初始化..完毕");
    }

    //将查询到的数据缓存到myCache中,并使用方法名称加上参数中的userNo作为缓存的key  
    //通常更新操作只需刷新缓存中的某个值,所以为了准确的清除特定的缓存,故定义了这个唯一的key,从而不会影响其它缓存值  
    @Cacheable(value = "ehcaheOne", key = "'get'+#userNo")
    public String get(String userNo) {
        System.out.println("数据库中查到此用户号[" + userNo + "]对应的用户名为[" + usersData.get(userNo) + "]");
        return usersData.get(userNo);
    }

    @CacheEvict(value = "ehcaheOne", key = "'get'+#userNo")
    public void update(String userNo) {
        System.out.println("移除缓存中此用户号[" + userNo + "]对应的用户名[" + usersData.get(userNo) + "]的缓存");
    }

    //allEntries为true表示清除value中的全部缓存,默认为false  
    @CacheEvict(value = "ehcaheOne", allEntries = true)
    public void removeAll() {
        System.out.println("移除缓存中的所有数据");
    }
}


首先是index.jsp

查看
	<a href="<%=request.getContextPath()%>/../test/get/2" target="_blank">2号</a>用户名
	<br />
	<br /> 查看
	<a href="<%=request.getContextPath()%>/../test/get/3" target="_blank">3号</a>用户名
	<br />
	<br /> 更新
	<a href="<%=request.getContextPath()%>/../test/update/3" target="_blank">3号</a>用户名
	<br />
	<br /> 移除
	<a href="<%=request.getContextPath()%>/../test/removeAll" target="_blank">所有</a>用户名

下面是 getUser.jsp  

当前用户名为${username}


下面是updateUser.jsp 

已更新${userNo}号用户

最后是removeAllUser.jsp

已移除所有用户

测试时,访问index.jsp之后点击各个链接并依次观察控制台输出即可
缓存有效果的特征是:第二次查询数据时不会访问数据库(即不打印日志)

项目整体部署图












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值