Java EhCache

来源:互联网 发布:国动网络通信集团待遇 编辑:程序博客网 时间:2024/05/24 05:47

1、配置文件ehcache-setting.xml

<?xml version="1.0" encoding="UTF-8"?><ehcache><!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 --><diskStore path="c:/tmp" /><!--缓存配置name:缓存名称。 maxElementsInMemory:缓存最大个数。 eternal:对象是否永久有效,一但设置了,timeout将不起作用。 timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。 overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。 diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。 maxElementsOnDisk:硬盘最大缓存个数。 diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false. diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 clearOnFlush:内存数量最大时是否清除。--><!-- 设定缓存的默认数据过期策略 --><defaultCache maxElementsInMemory="10000" eternal="false"overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="20"diskPersistent="true" diskExpiryThreadIntervalSeconds="120" /><cache name="hpCache" maxElementsInMemory="3000" eternal="false"overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="10000" timeToLiveSeconds="20000" /></ehcache>

 2、Java 代码直接调用

CacheManager manager = new CacheManager(new ClassPathResource("ehcache-setting.xml").getFile().getAbsolutePath()) ;System.out.println(Arrays.toString(manager.getCacheNames()));Cache cache = manager.getCache("hpCache");Element e1 = new Element("key1", "黄飞");Element e2 = new Element("key2", "hf");cache.put(e1);cache.put(e2);System.out.println( cache.get("key1"));System.out.println( cache.get("key2")) ;//使用flush,和 shutdown后才回持久化到磁盘上,这里和IO一样,不然 数据还在缓冲区域,不会溢写到磁盘cache.flush(); manager.shutdown(); 

 3、spring中使用

a、配置bean

@Bean(value = "ehcache")public EhCacheManagerFactoryBean ehcache() {EhCacheManagerFactoryBean ehcache = new EhCacheManagerFactoryBean();try {ehcache.setConfigLocation(new FileSystemResource(new ClassPathResource("ehcache-setting.xml").getFile()));} catch (Exception e) {e.printStackTrace();}return ehcache;}

 b、需要缓存的方法上加入注解

@Cacheable(value="hpCache")public long getTime(String param){  return System.currentTimeMillis() ;}

 c、调用测试

System.out.println(cacheService.getTime("1"));Thread.sleep(1000);System.out.println(cacheService.getTime("1"));

 

0 0
原创粉丝点击