您的位置:首页 > 编程语言 > Java开发

Spring如何配置数据库查询缓存/对象缓存EHCache

2016-06-08 19:45 465 查看
Spring如何配置查询缓存?  Ehcache可以对页面、对象、数据进行缓存,同时支持集群/分布式缓存。

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

EhCache是一种使用广泛的开源Java分布式缓存框架,它具有内存和磁盘存储,缓存加载器,缓存扩展,

缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP API。

优点:

1,快递;

2,简单;

3,多种缓存策略;

4,缓存数据有2种方式:内存和磁盘;

5,缓存数据会在虚拟机重启的过程中写入磁盘;

6,可以通过RMI、可插入API等方式实现;

7,提供Hibernate的缓存实现API;

缺点:

1,使用磁盘Cache的时候,占用磁盘空间较多,主要原因是DiskCache的算法简单;

2,不能保证数据的安全性,

一、准备工作

如果你的系统中已经成功加入Spring、Hibernate;那么你就可以进入下面Ehcache的准备工作。使用Spring

整合EhCache,可以灵活的对方法的返回结果对象进行缓存。

在ehcache.xml文件中配置查询缓存参数,ehcache.xml文件配置如下:

<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by

         its value in the running VM.

         The following properties are translated:

         user.home - User's home directory

         user.dir - User's current working directory

         java.io.tmpdir - Default temp file path -->

    <!-- diskStore元素,配置一个目录,这个目录用来存放数据,也就是说,如果EhCache需要把数据写入磁盘,将会写到这个目录下 -->

    <diskStore path="java.io.tmpdir"/>

    <!--Default Cache configuration. These will applied to caches programmatically created through

        the CacheManager.

        The following attributes are required:

        maxElementsInMemory            - Sets the maximum number of objects that will be created in memory

        eternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the

                                         element is never expired.

        overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache

                                         has reached the maxInMemory limit.

        The following attributes are optional:

        timeToIdleSeconds              - Sets the time to idle for an element before it expires.

                                         i.e. The maximum amount of time between accesses before an element expires

                                         Is only used if the element is not eternal.

                                         Optional attribute. A value of 0 means that an Element can idle for infinity.

                                         The default value is 0.

        timeToLiveSeconds              - Sets the time to live for an element before it expires.

                                         i.e. The maximum time between creation time and when an element expires.

                                         Is only used if the element is not eternal.

                                         Optional attribute. A value of 0 means that and Element can live for infinity.

                                         The default value is 0.

        diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.

                                         The default value is false.

        diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value

                                         is 120 seconds.

        -->

    <defaultCache

        maxElementsInMemory="10000"

        eternal="false"

        overflowToDisk="true"

        timeToIdleSeconds="120"

        timeToLiveSeconds="120"

        diskPersistent="false"

        diskExpiryThreadIntervalSeconds="120"/>

        

    <!-- See http://ehcache.sourceforge.net/documentation/#mozTocId258426 for how to configure caching for your objects -->

    

        <cache name="ehcacheName"

        maxElementsInMemory="3000"

        eternal="false"

        timeToIdleSeconds="3600"

        timeToLiveSeconds="36000"

        overflowToDisk="true"

        />

</ehcache>

参数说明:

name:缓存名称,配置缓存时,通过名称来调用缓存;

maxElementsOnDisk:磁盘中最大缓存的对象数,值为0表示无穷大;

maxElementsInMemory:内存中最大缓存对象数;

eternal:是否不过期,值为true表示永不过期,默认值为false;

timeToLiveSeconds:设置对象允许存在于缓存中的最长时间;

overflowToDisk:当缓存对象数达到了maxElementsInMemory设置的最大值以后,是否允许把溢出的对象写入到磁盘中;

diskSpoolBufferSizeMB:磁盘缓存区大小,默认值30MB;

timeToldleSeconds:设置允许对象处于空闲状态的最长时间,当对象离上次被访问的时间间隔超过了timeToldleSeconds属性值时,

这个对象就会过期,EhCache就会把它从缓存中清空;

memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,EhCache将会根据指定的策略去清理内存,可选策略有:

LRU(最近最少使用原则)/FIFO(先进先出)/LFU(最少访问次数)

二,Spring如何配置查询缓存示例

第一步:给指定方法配置缓存/mall-projectname/src/main/resources/applicationContext-resources.xml

<ehcache:proxy id="userGroupServiceProxy" refId="userGroupService" >

   <ehcache:caching cacheName="cash15Min"  methodName="selectuserGroupWithDetailByMemberId" />

   <ehcache:caching cacheName="cash15Min"  methodName="selectuserGroupWithDetailByGroupId" />

   <ehcache:caching cacheName="cash15Min"  methodName="selectuserGroupById" />

</ehcache:proxy>

配置参数的含义如下:

id:唯一标识符

refId:需要配置缓存的service或者controller

cacheName:缓存名称

methodName:需要缓存的方法,这个方法必须是shoppingHomeService中的方法

第二步:在控制器中注入依赖的缓存userGroupServiceProxy /mall-projectname/src/main/webapp/WEB-INF/dispatcher-servlet.xml

<bean id="PFController" class="com.java.mall.controller.PFController">

        <property name="userService" ref="userService"></property>

        <property name="userGroupService" ref="userGroupServiceProxy"></property>

</bean>

同时需要在实体类中注入依赖,提供setter方法,

private userGroupService userGroupService;

public void setuserGroupService(userGroupService userGroupService) {

this.userGroupService = userGroupService;

}

三,如何判断缓存配置成功?

看tomcat的控制台输出日志:

DEBUG [http-8089-39] EhCacheFacade.getFromCache(107) | Attempt to retrieve a cache entry using key <-117520639|-142320043> and cache model <org.springmodules.cache.provider.ehcache.EhCacheCachingModel@acdd8f[cacheName='cash15Min', blocking=false, cacheEntryFactory=null]>

DEBUG [http-8089-39] EhCacheFacade.getFromCache(125) | Retrieved cache element <[com.java.testshopping.user.model.userGroup@8ba25]>

在断点调试模式下,在调用查询方法之前,打一个断点,看控制台输出:

A,如果控制台输出的是上面这段日志,说明是从缓存中拿的数据;

B,如果控制台输出的是查询SQL,说明缓存配置失败;

关于缓存是一个比较系统的问题,这里仅作简要说明,稍后还会继续分享页面缓存的相关问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: