转载请注明出处:http://blog.csdn.net/dongdong9223/article/details/50538085

本文出自【我是干勾鱼的博客

1 Ehcache简单介绍

EhCache 是一个纯Java的进程内缓存框架。具有高速、精干等特点,是Hibernate中默认的CacheProvider。

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存载入器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。

Ehcache最初是由Greg Luck于2003年開始开发。

2009年,该项目被Terracotta购买。软件仍然是开源,但一些新的主要功能(比如,高速可重新启动性之间的一致性的)仅仅能在商业产品中使用,比如Enterprise EHCache and BigMemory。

维基媒体Foundationannounced眼下使用的就是Ehcache技术。

总之Ehcache还是一个不错的缓存技术,我们来看看Spring搭配Ehcache是怎样实现的。

2 Spring搭配Ehcache

系统结果例如以下:

3 详细配置介绍

有这几部分的结合:

  • src:java代码,包含拦截器,调用接口,測试类

  • src/cache-bean.xml:配置Ehcache。拦截器,以及測试类等信息相应的bean

  • src/ehcache.xml:Ehcache缓存配置信息

  • WebRoot/lib:库

4 详细内容介绍

4.1 src

4.1.1 拦截器

代码中首先配置了两个拦截器:

第一个拦截器为:

com.test.ehcache.CacheMethodInterceptor

内容例如以下:

package com.test.ehcache;

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element; import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert; public class CacheMethodInterceptor implements MethodInterceptor,
InitializingBean { private Cache cache; public void setCache(Cache cache) {
this.cache = cache;
} public CacheMethodInterceptor() {
super();
} /**
* 拦截ServiceManager的方法,并查找该结果是否存在,假设存在就返回cache中的值,
* 否则,返回数据库查询结果,并将查询结果放入cache
*/
public Object invoke(MethodInvocation invocation) throws Throwable {
//获取要拦截的类
String targetName = invocation.getThis().getClass().getName();
//获取要拦截的类的方法
String methodName = invocation.getMethod().getName();
//获得要拦截的类的方法的參数
Object[] arguments = invocation.getArguments();
Object result; //创建一个字符串。用来做cache中的key
String cacheKey = getCacheKey(targetName, methodName, arguments);
//从cache中获取数据
Element element = cache.get(cacheKey); if (element == null) {
//假设cache中没有数据,则查找非缓存,比如数据库,并将查找到的放入cache result = invocation.proceed();
//生成将存入cache的key和value
element = new Element(cacheKey, (Serializable) result);
System.out.println("-----进入非缓存中查找,比如直接查找数据库,查找后放入缓存");
//将key和value存入cache
cache.put(element);
} else {
//假设cache中有数据,则查找cache System.out.println("-----进入缓存中查找,不查找数据库。缓解了数据库的压力");
}
return element.getValue();
} /**
* 获得cache的key的方法,cache的key是Cache中一个Element的唯一标识,
* 包含包名+类名+方法名,如:com.test.service.TestServiceImpl.getObject
*/
private String getCacheKey(String targetName, String methodName,
Object[] arguments) {
StringBuffer sb = new StringBuffer();
sb.append(targetName).append(".").append(methodName);
if ((arguments != null) && (arguments.length != 0)) {
for (int i = 0; i < arguments.length; i++) {
sb.append(".").append(arguments[i]);
}
}
return sb.toString();
} /**
* implement InitializingBean,检查cache是否为空 70
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache,
"Need a cache. Please use setCache(Cache) create it.");
} }

CacheMethodInterceptor用来拦截以“get”开头的方法,注意这个拦截器是先拦截,后运行原调用接口。

另一个拦截器:

com.test.ehcache.CacheAfterReturningAdvice

详细内容:

package com.test.ehcache;

import java.lang.reflect.Method;
import java.util.List; import net.sf.ehcache.Cache; import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert; public class CacheAfterReturningAdvice implements AfterReturningAdvice,
InitializingBean { private Cache cache; public void setCache(Cache cache) {
this.cache = cache;
} public CacheAfterReturningAdvice() {
super();
} public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
String className = arg3.getClass().getName();
List list = cache.getKeys();
for (int i = 0; i < list.size(); i++) {
String cacheKey = String.valueOf(list.get(i));
if (cacheKey.startsWith(className)) {
cache.remove(cacheKey);
System.out.println("-----清除缓存");
}
}
} public void afterPropertiesSet() throws Exception {
Assert.notNull(cache,
"Need a cache. Please use setCache(Cache) create it.");
} }

CacheAfterReturningAdvice用来拦截以“update”开头的方法,注意这个拦截器是先运行原调用接口,后被拦截。

4.1.2 调用接口

接口名称为:

com.test.service.ServiceManager

详细内容例如以下:

package com.test.service;

import java.util.List;

public interface ServiceManager {
public List getObject(); public void updateObject(Object Object);
}

实现类名称为:

com.test.service.ServiceManagerImpl

详细内容例如以下:

package com.test.service;

import java.util.ArrayList;
import java.util.List; public class ServiceManagerImpl implements ServiceManager { @Override
public List getObject() {
System.out.println("-----ServiceManager:缓存Cache内不存在该element,查找数据库,并放入Cache! "); return null;
} @Override
public void updateObject(Object Object) {
System.out.println("-----ServiceManager:更新了对象,这个类产生的cache都将被remove!");
} }

4.1.3 測试类

測试类名称为:

com.test.service.TestMain

详细内容为:

package com.test.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestMain { public static void main(String[] args) { String cacheString = "/cache-bean.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(
cacheString);
//获代替理工厂proxyFactory生成的bean,以便产生拦截效果
ServiceManager testService = (ServiceManager) context.getBean("proxyFactory"); // 第一次查找
System.out.println("=====第一次查找");
testService.getObject(); // 第二次查找
System.out.println("=====第二次查找");
testService.getObject(); // 运行update方法(应该清除缓存)
System.out.println("=====第一次更新");
testService.updateObject(null); // 第三次查找
System.out.println("=====第三次查找");
testService.getObject();
}
}

此处要注意。获取bean是通过代理工厂proxyFactory生产的bean,这样才会有拦截效果。

可以看出来,在測试类里面设置了四次调用。运行顺序为:

  • 第一次查找
  • 第二次查找
  • 第一次更新
  • 第三次查找

4.2 src/cache-bean.xml

cache-bean.xml用来配置Ehcache。拦截器,以及測试类等信息相应的bean,内容例如以下:

<?xml version="1.0" encoding="UTF-8"?

>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 引用ehCache 的配置-->
<bean id="defaultCacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>ehcache.xml</value>
</property>
</bean> <!-- 定义ehCache的工厂,并设置所使用的Cache的name。即“com.tt” -->
<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="defaultCacheManager" />
</property>
<!-- Cache的名称 -->
<property name="cacheName">
<value>com.tt</value>
</property>
</bean> <!-- 创建缓存、查询缓存的拦截器 -->
<bean id="cacheMethodInterceptor" class="com.test.ehcache.CacheMethodInterceptor">
<property name="cache">
<ref local="ehCache" />
</property>
</bean> <!-- 更新缓存、删除缓存的拦截器 -->
<bean id="cacheAfterReturningAdvice" class="com.test.ehcache.CacheAfterReturningAdvice">
<property name="cache">
<ref local="ehCache" />
</property>
</bean> <!-- 调用接口,被拦截的对象 -->
<bean id="serviceManager" class="com.test.service.ServiceManagerImpl" /> <!-- 插入拦截器。确认调用哪个拦截器,拦截器拦截的方法名特点等,此处调用拦截器com.test.ehcache.CacheMethodInterceptor -->
<bean id="cachePointCut"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<!-- 增加切面。切面为当运行完print方法后。在运行增加的切面 -->
<property name="advice">
<ref local="cacheMethodInterceptor" />
</property>
<property name="patterns">
<list>
<!--
### .表示符合不论什么单一字元
### +表示符合前一个字元一次或多次
### *表示符合前一个字元零次或多次
### \Escape不论什么Regular expression使用到的符号
-->
<!-- .*表示前面的前缀(包含包名),意思是表示getObject方法-->
<value>.*get.*</value>
</list>
</property>
</bean> <!-- 插入拦截器,确认调用哪个拦截器,拦截器拦截的方法名特点等。此处调用拦截器com.test.ehcache.CacheAfterReturningAdvice -->
<bean id="cachePointCutAdvice"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="cacheAfterReturningAdvice" />
</property>
<property name="patterns">
<list>
<!-- .*表示前面的前缀(包含包名),意思是updateObject方法-->
<value>.*update.*</value>
</list>
</property>
</bean> <!-- 代理工厂 -->
<bean id="proxyFactory" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 说明调用接口bean名称 -->
<property name="target">
<ref local="serviceManager" />
</property>
<!-- 说明拦截器bean名称 -->
<property name="interceptorNames">
<list>
<value>cachePointCut</value>
<value>cachePointCutAdvice</value>
</list>
</property>
</bean>
</beans>

各个bean的内容都做了凝视说明,值得注意的是,不要忘了代理工厂bean。

4.3 src/ehcache.xml

ehcache.xml中存储Ehcache缓存配置的详细信息,内容例如以下:

<?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="D:\\temp\\cache" /> <defaultCache maxElementsInMemory="1000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
<!-- 定义缓存文件信息,当中“com.tt”为缓存文件的名字 -->
<cache name="com.tt" maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="300000" timeToLiveSeconds="600000" overflowToDisk="true" />
</ehcache>

可以看到缓存的存储的存储位置设置为“D:\temp\cache”。缓存名称设置成了“com.tt”,如图:

4.4 WebRoot/lib

所需的java库,详见开头的系统结构图片,此处略。

5 測试

运行測试类,測试结果例如以下:

通过运行结果我们可以看出:

第一次查找被拦截后发现是首次拦截,还没有缓存Cache。所以先运行一下原有接口类。得到要查询的数据,有可能是通过数据库查询得到的,然后再生成Cache,并将查询得到的数据放入Cache。

第二次查找被拦截后发现已经存在Cache。于是不再运行原有接口类,也就是不再查询数据库啦,直接通过Cache得到查询数据。当然这里仅仅是简单打印一下。

然后是第一次更新,被拦截后所做的操作是将Cache中的数据所有存入数据库,并将Cache删除。

最后是第三次查询。被拦截后又发现系统不存在Cache。于是运行原接口类查询数据库,创建Cache。并将新查询得到的数据放入Cache。同第一次查询的方式是一样的。

至此我们就实现了Spring搭配Ehcache所须要完毕的操作。

6 附件源码

附件源码可以从我的github站点上获取。

Spring搭配Ehcache实例解析的更多相关文章

  1. [Spring] AOP, Aspect实例解析

    最近要用到切面来统一处理日志记录,写了个小实例练了练手: 具体实现类: public interface PersonServer { public void save(String name); p ...

  2. Spring的AOP配置文件和注解实例解析

    1.1           Spring的AOP配置文件和注解实例解析 AOP它利用一种称为"横切"的技术,将那些与核心业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减 ...

  3. Spring系列(五):Spring AOP源码解析

    一.@EnableAspectJAutoProxy注解 在主配置类中添加@EnableAspectJAutoProxy注解,开启aop支持,那么@EnableAspectJAutoProxy到底做了什 ...

  4. Spring系列(六):Spring事务源码解析

    一.事务概述 1.1 什么是事务 事务是一组原子性的SQL查询,或者说是一个独立的工作单元.要么全部执行,要么全部不执行. 1.2 事务的特性(ACID) ①原子性(atomicity) 一个事务必须 ...

  5. Spring整合Ehcache管理缓存

    前言 Ehcache 是一个成熟的缓存框架,你可以直接使用它来管理你的缓存. Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现.它 ...

  6. Spring整合Ehcache管理缓存(转)

    目录 前言 概述 安装 Ehcache的使用 HelloWorld范例 Ehcache基本操作 创建CacheManager 添加缓存 删除缓存 实现基本缓存操作 缓存配置 xml方式 API方式 S ...

  7. Spring MVC之视图解析器

    Spring MVC提供的视图解析器使用ViewResolver进行视图解析,实现浏览器中渲染模型.ViewResolver能够解析JSP.Velocity模板.FreeMarker模板和XSLT等多 ...

  8. spring事务源码解析

    前言 在spring jdbcTemplate 事务,各种诡异,包你醍醐灌顶!最后遗留了一个问题:spring是怎么样保证事务一致性的? 当然,spring事务内容挺多的,如果都要讲的话要花很长时间, ...

  9. 【死磕 Spring】----- IOC 之解析 bean 标签:开启解析进程

    原文出自:http://cmsblogs.com import 标签解析完毕了,再看 Spring 中最复杂也是最重要的标签 bean 标签的解析过程. 在方法 parseDefaultElement ...

随机推荐

  1. LAMP安装细则

    利用xshell从Windows向Linux传输文件[root@nanainux ~]#yum install lrzsz[root@nanalinux ~]#rz  MySq二进制包安装 mysql ...

  2. rest_framework 权限流程

    权限流程 权限流程与认证流程非常相似,只是后续操作稍有不同 当用户访问是 首先执行dispatch函数,当执行当第二部时: #2.处理版本信息 处理认证信息 处理权限信息 对用户的访问频率进行限制 s ...

  3. 打印sql语句方法

    var_dump($this->blackpool_model->getLastSql());

  4. 使用threadpool并发测试,报错HTTPConnectionPool Max retires exceeded

    解决方法:和以下答案一致 https://blog.csdn.net/qq_21405949/article/details/79363084 场景: 在做爬虫项目或者是在发送网络请求的时候,一般都会 ...

  5. thinkphp函数学习(1)——header, get_magic_quotes_gpc, array_map, stripslashes, stripslashes_deep

    1. header 相关语句 header('Content-type: text/html; charset=utf-8'); // 因为这是在TP的入口文件中,所以每个页面返回的http head ...

  6. Codeforces 891B - Gluttony

    891B - Gluttony 题意 给出一个数字集合 \(a\),要求构造一个数组 \(b\) 为 \(a\) 的某个排列,且满足对于所有下标集合的子集 \(S=\{x_1,x_2,...,x_k\ ...

  7. ASP.NET Core 2.2 基础知识(十七) SignalR 一个极其简陋的聊天室

    这是一个极其简陋的聊天室! 这个例子只是在官方的例子上加了 Group 的用法而已,主要是官方给的 Group 的例子就两行代码,看不出效果. 第一步:修改 chat.js "use str ...

  8. 正则 lazy

  9. 2014 非常好用的开源 Android 测试工具

    http://www.php100.com/html/it/mobile/2014/1015/7495.html 当前有很大的趋势是转向移动应用平台,Android 是最广泛使用的移动操作系统,201 ...

  10. 【数论】【素数判定】CODEVS 2851 菜菜买气球

    素数判定模板. #include<cstdio> #include<map> using namespace std; ],ans=-,l,r,n,sum[]; bool is ...