spring缓存Ehcache(入门2)

使用Ehcache缓存工具类。

一.由于使用了maven,所以需要引入依赖包:

<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>
二.spring配置文件配置:
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"></property>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"/>
</bean>
三:相应的参数文件:ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache dynamicConfig="false" monitoring="off" updateCheck="false"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">

<!-- 定义缓存策略
eternal="false" // 元素是否永恒,如果是就永不过期(必须设置)
maxEntriesLocalHeap="1000" // 堆内存中最大缓存对象数,0没有限制(必须设置)
overflowToDisk="false" // 当缓存达到maxElementsInMemory值是,是否允许溢出到磁盘(必须设置)
diskPersistent="false" // 磁盘缓存在VM重新启动时是否保持(默认为false)
timeToIdleSeconds="0" // 导致元素过期的访问间隔(秒为单位). 当eternal为false时,这个属性才有效,0表示可以永远空闲,默认为0
timeToLiveSeconds="600" // 元素在缓存里存在的时间(秒为单位). 0 表示永远存在不过期
memoryStoreEvictionPolicy="LFU" // 当达到maxElementsInMemory时,如何强制进行驱逐默认使用"最近使用(LRU)"策略,其它还有先入先出FIFO,最少使用LFU,较少使用LRU
-->


<defaultCache eternal="false" maxEntriesLocalHeap="0" timeToIdleSeconds="300" timeToLiveSeconds="300"/>
<cache name="myCache" maxEntriesLocalHeap="1000" eternal="false" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU"/>


</ehcache>
四:demo类:service类
@Transactional(readOnly = true)
@Cacheable(value = "myCache" ,key = "#params")
public JsonObject getWFK(JsonObject params){
OneOb ob = new OneOb();
try {
List<Map<String,Object>> map = LawAssistantMapper.getWFK();
ob.setOb(map);
}catch (Exception e) {
e.printStackTrace();
ob.setCode(500);
ob.setMsg("服务器错误!!!");
return new JsonObject(Json.encode(ob));
}
ob.setCode(200);
ob.setMsg("ok");
logger.debug(Json.encode(ob));
return new JsonObject(Json.encode(ob));

}

优点:
看了不少资料,都说,Ehcache是最快的Java缓存之一。
对于没有在高并发,高流量的环境中使用过Ehcache的初级码民来说,没必要太深究。
我觉着,得先会用,没有师傅教,只能在使用过程中和别人的代码中积累使用经验。(小公司初级码民的悲哀~。)
原文地址:https://www.cnblogs.com/zqsky/p/5868549.html