缓存插件 EHCache 对象缓存(Spring)

对象缓存就是将查询的数据,添加到缓存中,下次再次查询的时候直接从缓存中获取,而不去数据库中查询。

对象缓存一般是针对方法、类而来的,结合Spring的Aop对象、方法缓存就很简单。这里需要用到切面编程,用到了Spring的MethodInterceptor或是用@Aspect。

代码如下:

package com.hoo.common.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.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

/**
 * <b>function:</b> 缓存方法拦截器核心代码
 * @author hoojo
 * @createDate 2012-7-2 下午06:05:34
 * @file MethodCacheInterceptor.java
 * @package com.hoo.common.ehcache
 * @project Ehcache
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
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();
    }

    /**
     * <b>function:</b> 返回具体的方法全路径名称 参数
     * @author hoojo
     * @createDate 2012-7-2 下午06:12:39
     * @param targetName 全路径
     * @param methodName 方法名称
     * @param arguments 参数
     * @return 完整方法名称
     */
    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();
    }
}

这里的方法拦截器主要是对你要拦截的类的方法进行拦截,然后判断该方法的类路径+方法名称+参数值组合的cache key在缓存cache中是否存在。如果存在就从缓存中取出该对象,转换成我们要的返回类型。没有的话就把该方法返回的对象添加到缓存中即可。值得主意的是当前方法的参数和返回值的对象类型需要序列化。

我们需要在src目录下添加applicationContext.xml完成对MethodCacheInterceptor拦截器的配置,该配置主意是注入我们的cache对象,哪个cache来管理对象缓存,然后哪些类、方法参与该拦截器的扫描。

添加配置如下:

<context:component-scan base-package="com.hoo.common.interceptor"/> 

<!-- 配置eh缓存管理器 -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>

<!-- 配置一个简单的缓存工厂bean对象 -->
<bean id="simpleCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
    <property name="cacheManager" ref="cacheManager" />
    <!-- 使用缓存 关联ehcache.xml中的缓存配置 -->
    <property name="cacheName" value="mobileCache" />
</bean>

<!-- 配置一个缓存拦截器对象,处理具体的缓存业务 -->
<bean id="methodCacheInterceptor" class="com. hoo.common.interceptor.MethodCacheInterceptor">
    <property name="cache" ref="simpleCache"/>
</bean>

<!-- 参与缓存的切入点对象 (切入点对象,确定何时何地调用拦截器) -->
<bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
    <!-- 配置缓存aop切面 -->
    <property name="advice" ref="methodCacheInterceptor" />
    <!-- 配置哪些方法参与缓存策略 -->
    <!--
        .表示符合任何单一字元
        ###  +表示符合前一个字元一次或多次
        ###  *表示符合前一个字元零次或多次
        ###  \Escape任何Regular expression使用到的符号
    -->
    <!-- .*表示前面的前缀(包括包名) 表示print方法-->
    <property name="patterns">
        <list>
            <value>com.hoo.rest.*RestService*\.*get.*</value>
            <value>com.hoo.rest.*RestService*\.*search.*</value>
        </list>
    </property>
</bean>

在ehcache.xml中添加如下cache配置

<cache name="mobileCache"
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="1800"
        timeToLiveSeconds="3600"
        memoryStoreEvictionPolicy="LFU" />
时间: 2024-12-14 18:09:02

缓存插件 EHCache 对象缓存(Spring)的相关文章

缓存插件 EHCache 页面缓存CachingFilter

Ehcache基本用法 CacheManager cacheManager = CacheManager.create(); // 或者 cacheManager = CacheManager.getInstance(); // 或者 cacheManager = CacheManager.create("/config/ehcache.xml"); // 或者 cacheManager = CacheManager.create("http://localhost:8080

缓存插件 EHCache

EHCache是来自sourceforge(http://ehcache.sourceforge.net/)的开源项目,也是纯Java实现的简单.快速的Cache组件. 下载jar包 Ehcache 对象.数据缓存:http://ehcache.org/downloads/destination?name=ehcache-core-2.5.2-distribution.tar.gz&bucket=tcdistributions&file=ehcache-core-2.5.2-distrib

Ehcache 整合Spring 使用页面、对象缓存

Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式缓存.如果整合Spring.Hibernate也非常的简单,Spring对Ehcache的支持也非常好.EHCache支持内存和磁盘的缓存,支持LRU.LFU和FIFO多种淘汰算法,支持分布式的Cache,可以作为Hibernate的缓存插件.同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度.

Ehcache 整合Spring 使用页面、对象缓存(转载)

Ehcache在很多项目中都出现过,用法也比较简单.一般的加些配置就可以了,而且Ehcache可以对页面.对象.数据进行缓存,同时支持集群/分布式缓存.如果整合Spring.Hibernate也非常的简单,Spring对Ehcache的支持也非常好.EHCache支持内存和磁盘的缓存,支持LRU.LFU和FIFO多种淘汰算法,支持分布式的Cache,可以作为Hibernate的缓存插件.同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度.

缓存插件 Spring支持EHCache缓存

Spring仅仅是提供了对缓存的支持,但它并没有任何的缓存功能的实现,spring使用的是第三方的缓存框架来实现缓存的功能.其中,spring对EHCache提供了很好的支持. 在介绍Spring的缓存配置之前,我们先看一下EHCache是如何配置. <?xml version="1.0" encoding="UTF-8" ?> <ehcache> <!-- 定义默认的缓存区,如果在未指定缓存区时,默认使用该缓存区 --> <

Spring整合Ehcache管理缓存

Ehcache 是一个成熟的缓存框架,你可以直接使用它来管理你的缓存. Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现.它支持注解方式使用缓存,非常方便.本文先通过Ehcache独立应用的范例来介绍它的基本使用方法,然后再介绍与Spring整合的方法. 概述 Ehcache是什么?EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点.它是Hibernate中的默认缓存框架.Ehcache已经发布了3.1版本

Spring控制Hibernate的缓存机制ehcache

首先在spring.xml中进入bean <prop key="hibernate.cache.use_second_level_cache">true</prop> <!--设置缓存机制为二级缓存 --> <prop key="hibernate.cache.use_query_cache">true</prop> <!--启动查询缓存 --> <prop key="hiber

springmvc结合ehcache实现共享对象缓存

笔者最近在学习Web性能优化的知识,想用springmvc结合ehcache来实现共享对象缓存,可是网上的很多教程讲得不是很清楚,加上本人对spring的知识还没有完全熟悉,所以在实现过程中碰到了各种各样的问题.现在将我的实验过程记录下来,以便以后回顾并且给广大正努力学习的同学参考参考.以下的代码基础是我自己本人写的小demo,具体功能以及实现请忽略,这里只关注缓存实现,并且默认大家已经都写过简单的springmvc项目,关于springmvc的配置就不多述. 具体实验步骤如下: 首先在之前的s

Spring缓存机制----EhCache缓存实现的配置

首先,需要添加连个jar包:ehcache-core-2.6.11.jar和slf4j-api-1.7.21.jar 在类加载路径下添加一个ehcache.xml配置文件,文件内容如下: <?xml version="1.0" encoding="utf-8"?> <ehcache> <diskStore path="java.io.tmpdir"/> <!-- 配置默认的缓存区 --> <d