ehcache 与spring相结合超时自动刷新缓存的框架搭建

简介: 我们在做J2EE工程中经常会碰到一些常量或者是一些不太用的数据。   这部分数据我们希望是把它放到一个共同的地方,然后大家都能去调用,而不用频繁调用数据库以提高web访问的效率。

我们在做J2EE工程中经常会碰到一些常量或者是一些不太用的数据。

 

这部分数据我们希望是把它放到一个共同的地方,然后大家都能去调用,而不用频繁调用数据库以提高web访问的效率。

 

这样的东西就是缓存(cache),对于缓存的正确理解是一块不太变动的数据,但是这块数据偶尔或者周期新会被变动的,如:

 

地区,分公司,省市。。。。。。

 

当系统一开始运行时,我们可以把一批静态的数据放入cache,当数据变化时,我们要从数据库把最新的数据拿出来刷新这块cache

 

我们以前的作法是做一个static 的静态变量,把这样的数据放进去,然后用一个schedule job定期去刷新它,然后在用户访问时先找内存,如果内存里没有找到再找数据库,找到数据库中的数据后把新的数据放入 cache

 

这带来了比较繁琐的编码工作,伴随而来的代码维护和性能问题也是很受影响的。

 

因此在此我们引入了ehcache组件。

 

目前市面上比较流行的是oscacheehcache,本人这一阵对两种cache各作了一些POC,作了一些比较,包括在cluster环境下的试用,觉得在效率和性能上两者差不多。

 

但是在配置和功能上ehcache明显有优势。

 

特别是spring2后续版本引入了对ehcache的集成后,更是使得编程者在利用缓存的问题上大为受益,我写这篇文章的目的就是为了使用SPRING AOP的功能,把调用维护ehcacheAPI函数封装入框架中,使得ehcache的维护对于开发人员来说保持透明。

  

Ehcache的配置件(ehcache.xml):

 

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="/tmp"/>

      

    <defaultCache

            maxElementsInMemory="500"

            eternal="false"

            timeToIdleSeconds="0"

            timeToLiveSeconds="60"

            overflowToDisk="false"

            maxElementsOnDisk="0"

            diskPersistent="false"

            diskExpiryThreadIntervalSeconds="0"

            memoryStoreEvictionPolicy="LRU"

            />

    <cache name="countryCache"

            maxElementsInMemory="10000"

            eternal="false"

            timeToIdleSeconds="0"

            timeToLiveSeconds="60"

            overflowToDisk="false"

            maxElementsOnDisk="0"

            diskPersistent="false"

            diskExpiryThreadIntervalSeconds="0"

            memoryStoreEvictionPolicy="LRU">

    </cache>

   

</ehcache>

 

1.必须要有的属性:

 

name: cache的名字,用来识别不同的cache,必须惟一。

 

maxElementsInMemory: 内存管理的缓存元素数量最大限值。

 

maxElementsOnDisk: 硬盘管理的缓存元素数量最大限值。默认值为0,就是没有限制。

 

eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。

 

overflowToDisk: 设定是否在内存填满的时候把数据转到磁盘上。

 

2.下面是一些可选属性:

 

timeToIdleSeconds 设定元素在过期前空闲状态的时间,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无限长时间。

 

timeToLiveSeconds: 设定元素从创建到过期的时间。其他与timeToIdleSeconds类似。

 

diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安全小型应用,宜设为true)

 

diskExpiryThreadIntervalSeconds: 访问磁盘线程活动时间。

 

diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有自己的缓冲区。

 

memoryStoreEvictionPolicy: 元素逐出缓存规则。共有三种,Recently Used (LRU)最近最少使用,为默认。 First In First Out (FIFO),先进先出。Less Frequently Used(specified as LFU)最少使用。

 

根据描述,上面我们设置了一个60秒过期不使用磁盘持久策略的缓存。

 

下面来看与spring的结合,我作一了个ehcacheBean.xml文件:

 

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

 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

                <bean id="defaultCacheManager"

                                class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">

                                <property name="configLocation">

                                                <value>classpath:ehcache.xml</value>

                                </property>

                </bean>

 

 

                <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">

                                <property name="cacheManager">

                                                <ref local="defaultCacheManager" />

                                </property>

                                <property name="cacheName">

                                                <value>countryCache</value>

                                </property>

                </bean>

 

                <bean id="methodCacheInterceptor" class="com.testcompany.framework.ehcache.MethodCacheInterceptor">

                                <property name="cache">

                                                <ref local="ehCache" />

                                </property>

                </bean>

 

             <bean id="methodCacheAfterAdvice" class="com.testcompany.framework.ehcache.MethodCacheAfterAdvice">

                                <property name="cache">

                                                <ref local="ehCache" />

                                </property>

                </bean>

 

                <bean id="methodCachePointCut"

                                class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">

                                <property name="advice">

                                                <ref local="methodCacheInterceptor" />

                                </property>

                                <property name="patterns">

                                                <list>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheFind*.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheGet*.*</value>

                                                </list>

                                </property>

                </bean>

                <bean id="methodCachePointCutAdvice"

                                class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">

                                <property name="advice">

                                                <ref local="methodCacheAfterAdvice" />

                                </property>

                                <property name="patterns">

                                                <list>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheCreate.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheUpdate.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheDelete.*</value>

                                                </list>

                                </property>

                </bean>

</beans> 

 

在此我定义了两个拦截器,一个叫MethodCacheInterceptor一个叫MethodCacheAfterAdvice

 

这两个拦截器的作用就是提供:

 

1.       用户调用ehcache时,自动先找ehcache中的对象,如果找不到再调用相关的service方法(如调用DB中的SQL来查询数据)。

 

它对以以下表达式的类方法作intercept:

 

                                                 <list>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheFind*.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheGet*.*</value>

                                                </list>

 

2.       为用户提供了一套管理ehcacheAPI函数,使得用户不用去写ehcacheapi函数来对ehcacheCRUD的操作

 

它对以以下表达式的类方法作after advice:

 

                                                <list>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheCreate.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheUpdate.*</value>

                                                                <value>com.testcompany.common.cache.EHCacheComponent.cacheDelete.*</value>

                                                </list>

 

我们一起来看这两个类的具体实现吧。

 

MethodCacheInterceptor.class

 

public class MethodCacheInterceptor implements MethodInterceptor,

                                InitializingBean {

                private final Log logger = LogFactory.getLog(getClass());

 

                private Cache cache;

 

                public void setCache(Cache cache) {

                                this.cache = cache;

                }

 

                public MethodCacheInterceptor() {

                                super();

                }

 

                @Override

                public Object invoke(MethodInvocation invocation) throws Throwable {

                                String targetName = invocation.getThis().getClass().getName();

                                String methodName = invocation.getMethod().getName();

                                Object[] arguments = invocation.getArguments();

                                Object result;

 

                                logger.info("Find object from cache is " + cache.getName());

 

                                String cacheKey = getCacheKey(targetName, methodName, arguments);

                                Element element = cache.get(cacheKey);

 

                                if (element == null) {

                                                logger

                                                                                .info("Can't find result in Cache , Get method result and create cache........!");

                                                result = invocation.proceed();

                                                element = new Element(cacheKey, (Serializable) result);

                                                cache.put(element);

                                }else{

                                                logger

                                                .info("Find result in Cache , Get method result and create cache........!");

                                }

                                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 < arguments.length; i++) {

                                                                sb.append(".").append(arguments[i]);

                                                }

                                }

                                return sb.toString();

                }

 

                public void afterPropertiesSet() throws Exception {

                                if (cache == null) {

                                                logger.error("Need a cache. Please use setCache(Cache) create it.");

                                }

                }

 

}

 

MethodCacheAfterAdvice

 

public class MethodCacheAfterAdvice implements AfterReturningAdvice,

                                InitializingBean {

 

                private final Log logger = LogFactory.getLog(getClass());

 

                private Cache cache;

 

                public void setCache(Cache cache) {

                                this.cache = cache;

                }

 

                public MethodCacheAfterAdvice() {

                                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);

                                                                logger.debug("remove cache " + cacheKey);

                                                }

                                }

                }

 

                public void afterPropertiesSet() throws Exception {

                                if (cache == null) {

                                                logger.error("Need a cache. Please use setCache(Cache) create it.");

                                }

                }

 

}

我们一起来看EHCacheComponent类的具体实现吧:

 

@Component

public class EHCacheComponent {

               

                protected final Log logger = LogFactory.getLog(getClass());

               

                @Resource

                private ICommonService commonService;

               

                public List<CountryDBO> cacheFindCountry()throws Exception{

                                return commonService.getCountriesForMake();

                }

}

 

该类中的方法cacheFindCountry()就是一个从缓存里找country信息的类。

因此,public List<CountryDBO> cacheFindCountry()是被cache的,每次调用时该方法都会被MethodCacheInterceptor拦截住,然后先去找cache,如果当在缓存里找到cacheFindCountry的对象后会直接返回一个list,如果没有,它会去调用servicegetCountriesForMake()方法。

 

现在来看我们原来的action的写法与更改成ehcache方式的写法。

 

               //List<CountryDBO> countries = commonService.getCountriesForMake();         /*原来在action中的调用*/

               

                List<CountryDBO> countries =cache.cacheFindCountry();                                         /*现在的调用*/

 

这时,用法登录主界面,查询国别信息,后台log日志报出:

 

2011-02-18 12:25:49  INFO MethodCacheInterceptor:33 - Find object from cache is countryCache

2011-02-18 12:25:49  INFO MethodCacheInterceptor:40 - Can't find result in Cache , Get method result and create cache........!

2011-02-18 12:25:49  INFO CommonDAOImpl:30 - >>>>>>>>>>>>>>>>>get counter for make from db

 

再次作国别信息的查询,后台log日志报出:

 

2011-02-18 11:58:26  INFO MethodCacheInterceptor:33 - Find object from cache is countryCache

2011-02-18 11:58:26  INFO MethodCacheInterceptor:46 - Find result in Cache , Get method result and create cache........!

 

 

此处的2011-02-18 12:25:49  INFO CommonDAOImpl:30 - >>>>>>>>>>>>>>>>>get counter for make from db语句是我故意放在调用数据库的dao方法开头的。

 

使得每次getCountriesForMakeservice方法去调用这个daodao. getCountriesForMake()方法时被log日志打印一下。

 

因此在60秒内我们做两次这样的国别信息查询,第一次是走dao,第二次没走DAO,但是国别信息也被查询出来了,大功告成。

 

最后:

 

ehcache.xml文件中的配置中的两个值的更改需要根据实际情况:

            timeToIdleSeconds="0"

            timeToLiveSeconds="60"

 

比如说如果你的国别过1个月会被客服人员更新一次,那可以把这个timeToLiveSeconds时间设置为一个月的秒。

timeToIdleSeconds这个值代表这个值如果在timeToLiveSeconds期内没人动,就会一直闲置着,而不会销毁。

目录
相关文章
|
5月前
|
安全 Java Ruby
我尝试了所有后端框架 — — 这就是为什么只有 Spring Boot 幸存下来
作者回顾后端开发历程,指出多数框架在生产环境中难堪重负。相比之下,Spring Boot凭借内置安全、稳定扩展、完善生态和企业级支持,成为构建高可用系统的首选,真正经受住了时间与规模的考验。
427 2
|
6月前
|
XML JSON Java
Spring框架中常见注解的使用规则与最佳实践
本文介绍了Spring框架中常见注解的使用规则与最佳实践,重点对比了URL参数与表单参数的区别,并详细说明了@RequestParam、@PathVariable、@RequestBody等注解的应用场景。同时通过表格和案例分析,帮助开发者正确选择参数绑定方式,避免常见误区,提升代码的可读性与安全性。
|
4月前
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
4月前
|
消息中间件 缓存 Java
Spring框架优化:提高Java应用的性能与适应性
以上方法均旨在综合考虑Java Spring 应该程序设计原则, 数据库交互, 编码实践和系统架构布局等多角度因素, 旨在达到高效稳定运转目标同时也易于未来扩展.
321 8
|
5月前
|
监控 Kubernetes Cloud Native
Spring Batch 批处理框架技术详解与实践指南
本文档全面介绍 Spring Batch 批处理框架的核心架构、关键组件和实际应用场景。作为 Spring 生态系统中专门处理大规模数据批处理的框架,Spring Batch 为企业级批处理作业提供了可靠的解决方案。本文将深入探讨其作业流程、组件模型、错误处理机制、性能优化策略以及与现代云原生环境的集成方式,帮助开发者构建高效、稳定的批处理系统。
634 1
|
7月前
|
安全 Java 微服务
Java 最新技术和框架实操:涵盖 JDK 21 新特性与 Spring Security 6.x 安全框架搭建
本文系统整理了Java最新技术与主流框架实操内容,涵盖Java 17+新特性(如模式匹配、文本块、记录类)、Spring Boot 3微服务开发、响应式编程(WebFlux)、容器化部署(Docker+K8s)、测试与CI/CD实践,附完整代码示例和学习资源推荐,助你构建现代Java全栈开发能力。
836 1
|
6月前
|
Cloud Native Java API
Java Spring框架技术栈选和最新版本及发展史详解(截至2025年8月)-优雅草卓伊凡
Java Spring框架技术栈选和最新版本及发展史详解(截至2025年8月)-优雅草卓伊凡
1275 0
|
7月前
|
缓存 安全 Java
第五章 Spring框架
Spring IOC(控制反转)通过工厂模式管理对象的创建与生命周期,DI(依赖注入)则让容器自动注入所需对象,降低耦合。常见注解如@Component、@Service用于声明Bean,@Autowired用于注入。Bean默认单例,作用域可通过@Scope配置,如prototype、request等。Spring通过三级缓存解决循环依赖问题,但构造函数循环依赖需用@Lazy延迟加载。AOP通过动态代理实现,用于日志、事务等公共逻辑。事务通过@Transactional实现,需注意异常处理及传播行为。
125 0
|
7月前
|
缓存 安全 Java
Spring 框架核心原理与实践解析
本文详解 Spring 框架核心知识,包括 IOC(容器管理对象)与 DI(容器注入依赖),以及通过注解(如 @Service、@Autowired)声明 Bean 和注入依赖的方式。阐述了 Bean 的线程安全(默认单例可能有安全问题,需业务避免共享状态或设为 prototype)、作用域(@Scope 注解,常用 singleton、prototype 等)及完整生命周期(实例化、依赖注入、初始化、销毁等步骤)。 解析了循环依赖的解决机制(三级缓存)、AOP 的概念(公共逻辑抽为切面)、底层动态代理(JDK 与 Cglib 的区别)及项目应用(如日志记录)。介绍了事务的实现(基于 AOP
267 0
|
7月前
|
存储 缓存 NoSQL
Spring Cache缓存框架
Spring Cache是Spring体系下的标准化缓存框架,支持多种缓存(如Redis、EhCache、Caffeine),可独立或组合使用。其优势包括平滑迁移、注解与编程两种使用方式,以及高度解耦和灵活管理。通过动态代理实现缓存操作,适用于不同业务场景。
618 0