/** * 缓存池 * @author xiaoquan * @create 2015年3月13日 上午10:32:13 * @see */publicclassCachePool { private staticCachePool instance;//缓存池唯一实例 privatestaticMap<String,Object> cacheItems;//缓存Map privateCachePool(){ cacheItems = newHashMap<String,Object>(); } /** * 得到唯一实例 * @return */ public synchronizedstaticCachePool getInstance(){ if(instance == null){ instance = newCachePool(); } returninstance; } /** * 清除所有Item缓存 */ publicsynchronized voidclearAllItems(){ cacheItems.clear(); } /** * 获取缓存实体 * @param name * @return */ publicsynchronizedObject getCacheItem(String name){ if(!cacheItems.containsKey(name)){ returnnull; } CacheItem cacheItem = (CacheItem) cacheItems.get(name); if(cacheItem.isExpired()){ returnnull; } returncacheItem.getEntity(); } /** * 存放缓存信息 * @param name * @param obj * @param expires */ publicsynchronizedvoidputCacheItem(String name,Object obj,longexpires){ if(!cacheItems.containsKey(name)){ cacheItems.put(name, newCacheItem(obj, expires)); } CacheItem cacheItem = (CacheItem) cacheItems.get(name); cacheItem.setCreateTime(newDate()); cacheItem.setEntity(obj); cacheItem.setExpireTime(expires); } publicsynchronizedvoidputCacheItem(String name,Object obj){ putCacheItem(name,obj,-1); } /** * 移除缓存数据 * @param name */ public synchronizedvoidremoveCacheItem(String name){ if(!cacheItems.containsKey(name)){ return; } cacheItems.remove(name); } /** * 获取缓存数据的数量 * @return */ publicint getSize(){ returncacheItems.size(); }}publicclassCacheItem { privateDate createTime = new Date();//创建缓存的时间 privatelongexpireTime = 1;//缓存期满的时间 privateObject entity;//缓存的实体 publicCacheItem(Object obj,longexpires){ this.entity = obj; this.expireTime = expires; } publicbooleanisExpired(){ return(expireTime != -1&& newDate().getTime()-createTime.getTime() > expireTime); } /** * 省略getter、setter方法 */} |
Original: http://www.cnblogs.com/quanenmin/p/4335278.html
Java Map Cache