ehcache缓存的简单使用
发布时间:2020-12-16 23:46:26 所属栏目:百科 来源:网络整理
导读:1、将ehcache.xml文件放到src目录下 ?xml version="1.0" encoding="UTF-8"?ehcache !-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -- diskStore path="java.io.tmpdir"/ !-- 默认缓存 -- defaultCache maxElementsInMemor
1、将ehcache.xml文件放到src目录下 <?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 --> <diskStore path="java.io.tmpdir"/> <!-- 默认缓存 --> <defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="20" diskPersistent="false" diskExpiryThreadIntervalSeconds="120"/> <!-- 自定义缓存 --> <cache name="cacheTest" maxElementsInMemory="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="10"/> </ehcache> 2、写个工具类 package com.common.utils; import java.net.URL; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; public class EhcacheUtil { private static String path = "/ehcache.xml"; private URL url; private CacheManager manager; private static EhcacheUtil cacheUtil; private EhcacheUtil(String path){ url = this.getClass().getResource(path); manager = CacheManager.create(url); } public static EhcacheUtil getInstance() { if(cacheUtil == null){ synchronized (EhcacheUtil.class) { if(cacheUtil == null){ cacheUtil = new EhcacheUtil(path); } } } return cacheUtil; } public void put(String cacheName,String key,Object value) { Cache cache = manager.getCache(cacheName); Element element = new Element(key,value); cache.put(element); } public Object get(String cacheName,String key) { Cache cache = manager.getCache(cacheName); Element element = cache.get(key); return element == null ? null : element.getObjectValue(); } public Cache get(String cacheName) { return manager.getCache(cacheName); } public void remove(String cacheName,String key) { Cache cache = manager.getCache(cacheName); cache.remove(key); } } 3、写个测试类 package com.test; import com.common.utils.EhcacheUtil; public class TestEhcache { public static void main(String[] args) { EhcacheUtil.getInstance().put("cacheTest","test","so easy!"); Object object = EhcacheUtil.getInstance().get("cacheTest","test"); System.out.println((String)object); } } 4、结束啦 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |