---
title: "ehcache缓存方法返回结果（一）-MethodCacheInterceptor"
author: "lastsoul"
date: "2015-09-28T16:01:46Z"
tags: []
categories: ["编程语言"]
slug: "ehcache-methodcacheinterceptor"
draft: false
lastmod: "2015-09-28T16:01:46Z"
id: 2246566
url: "https://lastsoul.iteye.com/blog/2246566"
---

对象缓存就是将查询的数据，添加到缓存中，下次再次查询的时候直接从缓存中获取，而不去数据库中查询。 对象缓存一般是针对方法、类而来的，结合Spring的Aop对象、方法缓存就很简单。这里需要用到切面编程，用到了Spring的MethodInterceptor 代码如下： \[code="java"]package com.last.cache.ehcache.filter; 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.apache.log4j.Logger; import org.springframework.beans.factory.InitializingBean; public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean { private static final Logger log = Logger.getLogger(MethodCacheInterceptor.class); private Cache cache; public void setCache(Cache cache) { this.cache = cache; } public void afterPropertiesSet() throws Exception { log.info(cache + " A cache is required. Use setCache(Cache) to provide one."); } public Object invoke(MethodInvocation invocation) throws Throwable { String targetName = invocation.getThis().getClass().getName(); String methodName = invocation.getMethod().getName(); Object\[] arguments = invocation.getArguments(); Object result; String cacheKey = getCacheKey(targetName, methodName, arguments); Element element = null; synchronized (this) { element = cache.get(cacheKey); if (element == null) { log.info(cacheKey + "加入到缓存： " + cache.getName()); // 调用实际的方法 result = invocation.proceed(); element = new Element(cacheKey, (Serializable) result); cache.put(element); } else { log.info(cacheKey + "使用缓存： " + cache.getName()); } } return element.getValue(); } 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 &lt; arguments.length; i++) { sb.append(".").append(arguments\[i]); } } return sb.toString(); } } \[/code] web.xml \[code="java"] contextConfigLocation classpath:spring-\*.xml org.springframework.web.context.ContextLoaderListener \[/code] spring-ehcache.xml \[code="java"] \[/code] AOP的配置展示了如何使用多个表达式，有一点要注意，过滤包名下的任意方法要多一个星，如：execution(* com.last.service.impl.\*.find\*(..)) 表示impl下及子包下的方法，并不能去掉这个星，变成execution(* com.last.service.impl.find\*(..)) ，表示impl下的方法也不能改成上面这样。