EHCache配置文件以及常用函数介绍

[b]
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(较少使用)。

ehcache中缓存的3种清空策略:
注: 是xml中的 memoryStoreEvictionPolicy 属性决定配置什么策略
1 FIFO,first in first out,这个是大家最熟的,先进先出

2 LFU, Less Frequently Used,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。

3 LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。

[/b]


import java.io.Serializable;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class Demo {

static CacheManager manager= new CacheManager();
//常用函数介绍
public static void main(String[] args) throws InterruptedException {

String[] cacheNames = manager.getCacheNames();
System.out.println("读取的缓存列表为:");
for(int i=0;i<cacheNames.length;i++){
System.out.println("-- "+(i+1)+" "+cacheNames[i]);
}

Cache cache = manager.getCache("cache1");
Element element = new Element("key1", "value1");
cache.put(element);

element = cache.get("key1");
Serializable value = element.getValue();
System.out.println("序列化后的值为:"+value.toString());

element = cache.get("key1");
Object value1 = element.getObjectValue();
System.out.println("未序列化的值为:"+value1.toString());

int elementsInMemory = cache.getSize();
System.out.println("得到缓存的对象数量:"+elementsInMemory);

long elementsInMemory1 = cache.getMemoryStoreSize();
System.out.println("得到缓存对象占用内存的数量:"+elementsInMemory1);

long elementsInMemory2 = cache.getDiskStoreSize();
System.out.println("得到缓存对对象占用磁盘的数量:"+elementsInMemory2);

int hits = cache.getHitCount();
System.out.println("得到缓存读取的命中次数:"+hits);

int hits1 = cache.getMemoryStoreHitCount();
System.out.println("得到内存中缓存读取的命中次数:"+hits1);

int hits2 =cache.getDiskStoreHitCount();
System.out.println("得到磁盘中缓存读取的命中次数:"+hits2);

int hits3 = cache.getMissCountNotFound();
System.out.println("得到缓存读取的丢失次数:"+hits3);

int hits4 = cache.getMissCountExpired();
System.out.println("得到缓存读取的已经被销毁的对象丢失次数:"+hits4);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值