大致思路是用一个单例的Map实现,当然此Map得是线程安全的--ConcurrentHashMap
原本项目需求是缓存十条消息,所以打算用Map实现缓存机制。中途夭折下面具体尚未实现。。。
当然此代码仞为半成品,具体得根据项目需求采用不同的原则清除缓存
1 package per.zww.util; 2 3 import java.util.Map; 4 import java.util.concurrent.ConcurrentHashMap; 5 6 public class CachePool { 7 private static CachePool cachePool; 8 private Map<Object, Object> cacheItems; 9 private CachePool() { 10 cacheItems =new ConcurrentHashMap<Object, Object>(); 11 } 12 /** 13 * 获取唯一实例 14 * @return instance 15 */ 16 public static CachePool getInstance() { 17 if (cachePool ==null) { 18 synchronized (CachePool.class) { 19 if (cachePool ==null) { 20 cachePool =new CachePool(); 21 } 22 } 23 } 24 return cachePool; 25 } 26 27 /** 28 * 获取所有cache信息 29 * @return cacheItems 30 */ 31 public Map<Object, Object> getCacheItems() { 32 return this.cacheItems; 33 } 34 35 /** 36 * 清空cache 37 */ 38 public void clearAllItems() { 39 cacheItems.clear(); 40 } 41 42 /** 43 * 获取指定cache信息 44 * @return cacheItem 45 */ 46 public Object getCacheItem(Object key) { 47 if (cacheItems.containsKey(key)) { 48 return cacheItems.get(key); 49 } 50 return null; 51 } 52 53 /** 54 * 存放cache信息 55 */ 56 public void putCacheItem(Object key,Object value) { 57 if (!cacheItems.containsKey(key)) { 58 cacheItems.put(key, value); 59 } 60 } 61 62 /** 63 * 删除一个cache 64 */ 65 public void removeCacheItem(Object key) { 66 if (cacheItems.containsKey(key)) { 67 cacheItems.remove(key); 68 } 69 } 70 71 /** 72 * 获取cache长度 73 * @return size 74 */ 75 public int getSize() { 76 return cacheItems.size(); 77 } 78 79 }