之前只是聽說過緩存池,也沒有具體的接觸到,今天做項目忽然想到了用緩存池,就花了一上午的時間研究了下緩存池的原理,並實現了基本的緩存池功能。
/** * 緩存池 * @author xiaoquan * @create 2015年3月13日 上午10:32:13 * @see */ public class CachePool { private static CachePool instance;//緩存池唯一實例 private static Map<String,Object> cacheItems;//緩存Map private CachePool(){ cacheItems = new HashMap<String,Object>(); } /** * 得到唯一實例 * @return */ public synchronized static CachePool getInstance(){ if(instance == null){ instance = new CachePool(); } return instance; } /** * 清除所有Item緩存 */ public synchronized void clearAllItems(){ cacheItems.clear(); } /** * 獲取緩存實體 * @param name * @return */ public synchronized Object getCacheItem(String name){ if(!cacheItems.containsKey(name)){ return null; } CacheItem cacheItem = (CacheItem) cacheItems.get(name); if(cacheItem.isExpired()){ return null; } return cacheItem.getEntity(); } /** * 存放緩存信息 * @param name * @param obj * @param expires */ public synchronized void putCacheItem(String name,Object obj,long expires){ if(!cacheItems.containsKey(name)){ cacheItems.put(name, new CacheItem(obj, expires)); } CacheItem cacheItem = (CacheItem) cacheItems.get(name); cacheItem.setCreateTime(new Date()); cacheItem.setEntity(obj); cacheItem.setExpireTime(expires); } public synchronized void putCacheItem(String name,Object obj){ putCacheItem(name,obj,-1); } /** * 移除緩存數據 * @param name */ public synchronized void removeCacheItem(String name){ if(!cacheItems.containsKey(name)){ return; } cacheItems.remove(name); } /** * 獲取緩存數據的數量 * @return */ public int getSize(){ return cacheItems.size(); } }
public class CacheItem { private Date createTime = new Date();//創建緩存的時間 private long expireTime = 1;//緩存期滿的時間 private Object entity;//緩存的實體 public CacheItem(Object obj,long expires){ this.entity = obj; this.expireTime = expires; } public boolean isExpired(){ return (expireTime != -1 && new Date().getTime()-createTime.getTime() > expireTime); } /** * 省略getter、setter方法 */ }