各位IT同事们:
你们好,我是一名小小的IT程序员。最近无聊想写写博客,提升一下自己,这部最近公司项目使用缓存redis ,由于高并发下环境下,redis 缓存撑不住,同时公司架构师建议使用Eache二级缓存。了解了一下。为大家介绍下Ehache 和 Spring 整合 使用注解的方式。话不多说,首先就介绍一下Ehcache。
1. Ehcache简介
1.Ehcache是一非常轻量级别的缓存实现。是一个纯java进程内的缓存框架,Ehcache 具有两种存储方式:内存和磁盘
2.Ehcache特点
1.快速
2.简单
3.可以远程调用(RMI)和通过插入API的方式进行分布式缓存
4.支持多种缓存策略(FIFO:先进先出,LRE:最近未使用的,LFE:最近少使用的 )
5.可以和hibernate 整合使用
3.配置Ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
上述代码 就是定义一个ehcache.xml文件 定义一个xml必须遵循Xml Schemal的定义 我们可以使用在线的ehcache.xsd 如:http://ehcache.org/ehcache.xsd 也可以将在线的ehcache.xsd下载到本地,然后拷贝到你的目录下
<diskStore path ="java.io.tmpdir">
<diskStore>元素:指定一个目录,把Ehcache 缓存的数据写入硬盘上时,然后在将把这个数据写入这个文件目录下 元素有path:
user.home 用户主目录
user.dir 用户当前工作目录
java.io.tmpdir 默认临时文件路径。
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<defaultCache>:
属性有:maxElementsInMemory :设置该对象缓存到内存的最大的数目
eternal:设置该对象缓存到内存是否永远不过期,默认为false ,如果为true,则会忽略掉 timeToldleSeconds和timeToliveSeconds
timeToldeSeconds:允许对象处于空间时间为多久,以秒为单位。当对象第一次访问后,如果超过了空闲时间,没有访问,那么会被清理掉
timeToLiveSeconds:允许对象对象处于缓存中多少时间,以秒为单位,如果当对象超过了缓存时间,那么该对象就会过期,当对象过期后,EHcache 将清理过期对象
overFlowToDisk:如果该内存中的对象超过了maxElementsMemory 后,会将该对象写入硬盘的缓存中,只有该对象实现了Serializable接口才行
memoryStoreEvictionPolicy:设置对象清除策略
FIFO:先进先出
LFU:一直以来最少被使用的先清除
LRU:最近被最少使用的
Spring 整合 Ehcache 如何
1.加入cache 头文件名 xmlns:cache="http://www.springframework.org/schema/cache"
2.加入cache.xsd文件 http://www.springframework.org/schema/cachehttp://www.springframework.org/schema/cache/spring-cache.xsd
3.启用Ehcache激活spring缓存注解
<cache :annotation-driven cache-manager="cacheManager">
4.加入缓存管理器
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="cacheManager" ref="ehCacheManager" /></bean>
5.引入ehcache.xml
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:spring/ehcache.xml"/>
</bean>
上述描述为Spring 整合 Ehache ,有不对的地方,请指出。
------------------------一名萌新程序员