1. Ehcache
EHCache是来自sourceforge(http://ehcache.sourceforge.net/)的开源项目,也是纯Java实现的简单、快速的Cache组件。EHCache支持内存和磁盘的缓存,支持LRU、LFU和FIFO多种淘汰算法;
Ehcache配置:
在mybatis配置文件里面启用缓存
<settings> <setting name="cacheEnabled" value="true" /> </settings>
2. 建立ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <defaultCache overflowToDisk="true" eternal="false"/> <diskStore path="D:/cache" /> <cache name="zzugxy" overflowToDisk="true" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" maxElementsInMemory="1000" diskPersistent="true" diskExpiryThreadIntervalSeconds="300" memoryStoreEvictionPolicy="LRU" /> </ehcache>
<diskstore>是指定缓存地点 可以指定为java.io.tmpdir
<cache/>参数详情:
name:Cache的唯一标识
maxElementsInMemory:内存中最大缓存对象数
maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大
eternal:Element是否永久有效,一但设置了,timeout将不起作用
overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中
timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大
diskPersistent:是否缓存虚拟机重启期数据
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)
3. 在Spring配置文件里面写入ehcache的bean,引入ehcache的xml文件
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml" /> </bean>
4. 在需要做缓存的Mapper里面加入使用缓存的标识
<cache type="org.mybatis.caches.ehcache.LoggingEhcache" > <property name="timeToIdleSeconds" value="3600"/> <property name="timeToLiveSeconds" value="3600"/> <property name="maxEntriesLocalHeap" value="1000"/> <property name="maxEntriesLocalDisk" value="10000000"/> <property name="memoryStoreEvictionPolicy" value="LRU"/> </cache>
2. Redis
使用redis作为缓存,目前没有专门的Jar可以实现,需要手动写代码实现mybatis里面
的Cache接口,在执行语句的时候将获取到的结果对象放进redis里面;结果对象和key都需要序列化
Redis配置步骤:
在mybatis配置文件里面启用缓存
<settings> <setting name="cacheEnabled" value="true" /> </settings>
2. 在需要启用缓存的Mapper里面配置
<cache eviction="LRU" type="com.guoxin.module.datastat.dao.MybatisRedisCache" />
其中type就是我们实现Cache接口的类
3. 剩下的就是实现Cache接口了
3. 二级缓存补充说明
映射语句文件中的所有select语句将会被缓存。
映射语句文件中的所有insert,update和delete语句会刷新缓存。
缓存会使用Least Recently Used(LRU,最近最少使用的)算法来收回。
缓存会根据指定的时间间隔来刷新。
缓存会存储1024个对象
4. 测试结果
使用ehcache,第一次获取数据用时7454ms,稳定之后每次获取数据都在100ms左右;
使用redis,第一次获取数据用时7625ms,稳定之后每次获取数据都在100ms左右;但是出现过一次15000ms的时间,还是在有缓存之后,不知道这个是从哪里来的,猜测是读写锁导致的