缓存的作用
缓存(Cache)是一块为提升系统性能而开辟出来的内存空间。其主要作用是暂存数据处理结果,并提供下次访问使用。在很多场合,数据的处理或者数据获取可能非常费时,当对这个数据的请求量很大时,频繁的数据处理会消耗大量资源。缓存的作用就是将这些来之不易的数据存储起来,当再次请求此数据时,直接从缓存中获取而省略数据处理流程,从而降低资源的消耗提高响应速度。
EhCache配置文件
<ehcache>
<!--缓存文件位置-->
<diskStore path="/data/ehcache"/>
<defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120"
timeToLiveSeconds="120" diskPersistent="false" diskExpiryThreadIntervalSeconds="120"/>
<cache name="cache" maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120"
timeToLiveSeconds="120" diskPersistent="false"/>
</ehcache>
EhCache配置文件说明
maxElementsInMemory:该缓存中允许存放的最大条目数
eternal:缓存内容是否永久缓存
overflowToDisk:如果内存中的数据超过maxElementsInMemory,是否使用磁盘存储
timeToIdleSeconds:如果不是永久存储的缓存,那么在timeToIdleSeconds指定时间内没有访问一个条目,则移除它
timeToLiveSeconds:如果不是永久存储的缓存,一个条目可以存在的最长时间
diskPersistent:磁盘存储的条目是否永久保存
diskExpiryThreadIntervalSeconds:磁盘清理线程的运行时间间隔
EhCache工具类
/**
* Created by YangJinyou on 2018/07.
* EhCache工具类
*/
public class EhCacheUtil {
private static CacheManager manage;
static {
//载入EhCache配置文件,创建CacheManager
manage = CacheManager.create(EhCacheUtil.class.getResourceAsStream("/cache/ehcache.xml"));
}
/**
* 将数据存入缓存
*
* @param cacheName
* @param key
* @param value
*/
public static void put(String cacheName, Serializable key, Serializable value) {
manage.getCache(cacheName).put(new Element(key, value));
}
/**
* 从缓存中取出数据
*
* @param cacheName
* @param key
* @return
*/
public static Serializable get(String cacheName, Serializable key) {
try {
Element e = manage.getCache(cacheName).get(key);
if (e != null) {
return e.getValue();
}
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (CacheException e1) {
e1.printStackTrace();
} catch (ClassCastException e1) {
e1.printStackTrace();
}
return null;
}
}