继续上篇,这篇介绍服务层缓存,ehcache一般的配置和用法

一、添加jar包引用

修改pom.xml文件,加入:

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>

除了之前加入的ehcache-core包,还需要加入spring-context-support包(包含EhCacheManagerFactoryBean)

二、添加配置文件

1、在"src/main/resources"代码文件夹中新建文件"spring-context-ehcache.xml":

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <description>Ehcache Configuration</description> <!-- 使用Annotation自动注册Bean -->
<context:component-scan base-package="org.xs.techblog" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan> <!-- 缓存配置 -->
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache-context.xml" />
</bean>
</beans>

ehcache的CacheManager就是通过spring提供的ehCacheManagerFactoryBean生成的,configLocation项设置了ehcache的配置文件地址。

2、在"src/main/resources"代码文件夹中新建文件"ehcache-context.xml":

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="defaultCache">
<!--默认的缓存配置(可以给每个实体类指定一个对应的缓存,如果没有匹配到该类,则使用这个默认的缓存配置)-->
<defaultCache
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="100000"
overflowToDisk="true"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
/> <!-- 指定缓存存放在磁盘上的位置 -->
<diskStore path="java.io.tmpdir/demo1/ehcache/hibernate" />
</ehcache>

用来专门配置缓存里用到的cache,文件内容和上一篇的ehcache-hibernate.xml大致一样,不过需要在<ehcache name="xxx"内设置一个别名,不然会和之前的重复,tomcat会运行不通过。

三、添加CacheUtils工具类

在"src/main/java"代码文件夹的"org.xs.demo1"的包下新建"CacheUtils.java"类:

package org.xs.demo1;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element; /**
* Cache工具类
*/
public class CacheUtils { private static CacheManager cacheManager = ((CacheManager)ContextUtils.getBean("ehcacheManager")); public static Object get(String cacheName, String key) {
Element element = getCache(cacheName).get(key);
return element==null?null:element.getObjectValue();
} public static void put(String cacheName, String key, Object value) {
Element element = new Element(key, value);
getCache(cacheName).put(element);
} public static void remove(String cacheName, String key) {
getCache(cacheName).remove(key);
} private static Cache getCache(String cacheName){
Cache cache = cacheManager.getCache(cacheName);
if (cache == null){
cacheManager.addCache(cacheName);
cache = cacheManager.getCache(cacheName);
}
return cache;
} public static CacheManager getCacheManager() {
return cacheManager;
}
}

CacheUtils读取了"ehcacheManager"bean的地址,可以创建和使用cache。

ContextUtils提供了getBean的方法,是一个很常用的工具类,内容是:

package org.xs.demo1;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service; /**
* 获得ApplicaitonContext的工具.
*/
@Service
@Lazy(false)
public class ContextUtils implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; /**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
} /**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
ContextUtils.applicationContext = applicationContext;
} /**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
applicationContext = null;
}
}

四、运行测试

1、修改HelloController.java类的list方法:

@SuppressWarnings("unchecked")
@RequestMapping("list")
public String list(HttpServletRequest request) { //先从缓存中获取list
List<testInfo> list = (List<testInfo>)CacheUtils.get("test", "testList");
if(list == null) {
list = testDao.getList();
//将list存入缓存
CacheUtils.put("test", "testList", list);
} //如果修改了test的数据后要马上体现,可以手动清空list缓存
//CacheUtils.remove("test", "testList"); request.setAttribute("testList", list); return "list";
}

2、测试

访问"http://localhost:8080/demo1/hello/list":

第一次访问,缓存里没有list,进入断点

第二次访问,缓存里已经有list了

实例代码地址:https://github.com/ctxsdhy/cnblogs-example

spring中ehcache的配置和使用方法的更多相关文章

  1. spring+hibernate 配置多个数据源过程 以及 spring中数据源的配置方式

    spring+hibernate 配置多个数据源过程 以及 spring中数据源的配置方式[部分内容转载] 2018年03月27日 18:58:41 守望dfdfdf 阅读数:62更多 个人分类: 工 ...

  2. 浅谈Spring中的Quartz配置

    浅谈Spring中的Quartz配置 2009-06-26 14:04 樊凯 博客园 字号:T | T Quartz是一个强大的企业级任务调度框架,Spring中继承并简化了Quartz,下面就看看在 ...

  3. Spring中三种配置Bean的方式

    Spring中三种配置Bean的方式分别是: 基于XML的配置方式 基于注解的配置方式 基于Java类的配置方式 一.基于XML的配置 这个很简单,所以如何使用就略掉. 二.基于注解的配置 Sprin ...

  4. spring中MessageSource的配置使用方法3--ResourceBundleMessageSource【转】

    本文转载仅供自己学习收录,不做任何商业用途,如有需要请访问原地址:http://blog.csdn.net/qyf_5445/article/details/8124431 ApplicationCo ...

  5. spring中MessageSource的配置使用方法3--ResourceBundleMessageSource

    ApplicationContext接口扩展了MessageSource接口,因而提供了消息处理的功能(i18n或者国际化).与HierarchicalMessageSource一起使用,它还能够处理 ...

  6. Quartz 在 Spring 中如何动态配置时间--转

    原文地址:http://www.iteye.com/topic/399980 在项目中有一个需求,需要灵活配置调度任务时间,并能自由启动或停止调度. 有关调度的实现我就第一就想到了Quartz这个开源 ...

  7. Spring 中的 Bean 配置

    内容提要 •IOC & DI 概述 •配置 bean –配置形式:基于 XML 文件的方式:基于注解的方式 –Bean 的配置方式:通过全类名(反射).通过工厂方法(静态工厂方法 & ...

  8. Spring中bean的配置

    先从IOC说起,这个概念其实是从我们平常new一个对象的对立面来说的,我们平常使用对象的时候,一般都是直接使用关键字类new一个对象,那这样有什么坏处呢?其实很显然的,使用new那么就表示当前模块已经 ...

  9. Spring中Quartz的配置

    Quartz是一个强大的企业级任务调度框架,Spring中继承并简化了Quartz,下面就看看在Spring中怎样配置Quartz: 首先,来写一个测试被调度的类:(QuartzHelloWorldJ ...

随机推荐

  1. MySQL隔离性及Spring事务

    一.数据库事务ACID特性 必须要掌握事务的4个特性,其中事务的隔离性之于MySQL,对应4级隔离级别. 原子性(Atomicity): 事务中的所有原子操作,要么都能成功完成,要么都不完成,不能停滞 ...

  2. cookie、session和application都是些什么神?——图文加案例,不怕你不会,就怕你不看

    cookie.session和application都是些什么神? 前言: 一直想写一篇关于cookie和session的博客,由于种种原因,一直没有整理,这不,今天还就遇到问题了,之前虽然会,但是好 ...

  3. python 之os模块用法大全

    Python的标准库中的os模块包含普遍的操作系统功能.这个模块的作用主要是提供与平台无关的功能.也就是说os模块能够处理平台间的差异问题,使得编写好的程序无需做任何改动就能在另外的平台上运行 这边给 ...

  4. 逆向破解之160个CrackMe —— 018

    CrackMe —— 018 160 CrackMe 是比较适合新手学习逆向破解的CrackMe的一个集合一共160个待逆向破解的程序 CrackMe:它们都是一些公开给别人尝试破解的小程序,制作 c ...

  5. 借助腾讯云的云函数实现一个极简的API网关

    借助腾讯云的云函数实现一个极简的API网关 Intro 微信小程序的域名需要备案,但是没有大陆的服务器,而且觉得备案有些繁琐,起初做的小程序都有点想要放弃了,后来了解到腾讯云的云函数,于是利用腾讯云的 ...

  6. python多进程通信实例分析

    操作系统会为每一个创建的进程分配一个独立的地址空间,不同进程的地址空间是完全隔离的,因此如果不加其他的措施,他们完全感觉不到彼此的存在.那么进程之间怎么进行通信?他们之间的关联是怎样的?实现原理是什么 ...

  7. 【原创】Linux PSCI框架

    背景 Read the fucking source code! --By 鲁迅 A picture is worth a thousand words. --By 高尔基 说明: Kernel版本: ...

  8. stage_ros的world文件配置方法

    官方文档参阅:http://rtv.github.io/Stage/modules.html stage_ros是一个基于stage的2D模拟器,用于ROS的仿真测试.虽然现在越来越多的人在使用gaz ...

  9. Python 基础(二)

    输入一个字符串,以列表输出大写,如果包含整数,转为整型 str = input() list = [] for i in str: if i.isdecimal() == True: list.app ...

  10. Python数据类型详解——字典

    Python数据类型详解--字典 引子 已经学习了列表,现在有个需求--把公司每个员工的姓名.年龄.职务.工资存到列表里,你怎么存? staff_list = [ ["Kwan", ...