继续上篇,这篇介绍服务层缓存,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

最新文章

  1. python学习5 常用三方模块
  2. zlib的安装
  3. asp.net JavaScriptSerializer实现序列化和反序列化
  4. Python循环嵌套
  5. Careercup - Google面试题 - 6271724635029504
  6. Storm系列(十二)架构分析之Worker-心跳信息处理
  7. phpmyadmin上传较大sql文件
  8. ENVI5.1批量镶嵌工具界面按钮显示不全的解决方案
  9. JAVA并发,线程异常捕获
  10. Android学习笔记之Broadcast Receiver
  11. MyBatis之级联小结
  12. Java并发系列[4]----AbstractQueuedSynchronizer源码分析之条件队列
  13. Mininet简介
  14. Django中过期@cache_page中缓存的views数据
  15. 微服务架构-选择Spring Cloud,放弃Dubbo
  16. python 全栈开发,Day11(函数名应用,闭包,装饰器初识,带参数以及带返回值的装饰器)
  17. MySQL--线程池(Thread Pool)
  18. POJ1811(SummerTrainingDay04-G miller-rabin判断素性 &amp;&amp; pollard-rho分解质因数)
  19. Python使用MySQLConnector/Python操作MySQL、MariaDB数据库
  20. Airmon-ng抓包&amp;破解wifi

热门文章

  1. list 列表常用方法
  2. 玩转 SpringBoot 2 快速搭建 | IntellJ IDEA篇
  3. Docker学习总结(七)--Docker私有仓库
  4. 安装VMware Workstation时遇到Microsoft Runtime DLL安装程序未能完成安装
  5. JDBC之PreparedStatement
  6. 转载-Springboot整合ehcache缓存
  7. PHP文件基础操作
  8. [python]python子字符串的提取、字符串连接、字符串重复
  9. HDU4289Control 无向图拆点最大流
  10. 2018CCPC 吉林现场赛 赛后总结