zoukankan      html  css  js  c++  java
  • 缓存插件 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 hoojo_@126.com
     * @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" />
  • 相关阅读:
    基于NEO4J的高级检索功能
    Neo4j 3.5发布,在索引方面大幅增强
    Neo4j 全文检索
    主流图数据库Neo4J、ArangoDB、OrientDB综合对比:架构分析
    neo4j常用cypher语句
    Neo4j使用简单例子
    neo4j 初探
    neo4j 基本概念和Cypher语句总结
    NEO4J亿级数据全文索引构建优化
    自定义中文全文索引
  • 原文地址:https://www.cnblogs.com/hwaggLee/p/4443163.html
Copyright © 2011-2022 走看看