通过HashMap进行缓存
private static Map<String, Object>cacheMap; public staticObject getCache(String key, Object defaultValue) { Object obj =getCacheMap().get(key); //Object obj = getSession().getAttribute(key); return obj==null?defaultValue:obj; } public static voidputCache(String key, Object value) { getCacheMap().put(key, value); //getSession().setAttribute(key, value); } public static voidremoveCache(String key) { getCacheMap().remove(key); //getSession().removeAttribute(key); } public static Map<String, Object>getCacheMap() { if (cacheMap==null){ cacheMap = new HashMap<String, Object>(); } returncacheMap; }
通过LinkedHashMap实现:
/** * 使用的是LinkedHashMap实现 */ public class LRU<K, V> extends LinkedHashMap<K, V>{ private static final long serialVersionUID = 1L; //缓存大小 private intcachaSize; public LRU(intcachaSize) { super(10, 0.75f, true); this.cachaSize =cachaSize; } /*** 缓存是否已满 */@Override protected boolean removeEldestEntry(Map.Entry<K, V>eldest) { boolean r = size() >cachaSize; if(r) { System.out.println("清除缓存key:" +eldest.getKey()); } returnr; } }
ConcurrentHashMap的本地缓存实现:与Guava cache相比,ConcurrentHashMap需要自己显式的删除缓存
importjava.util.concurrent.ConcurrentHashMap; public classConcurrentHashMapTest { private static ConcurrentHashMap<String, String> cacheMap = new ConcurrentHashMap<>(); /*** 获取缓存的对象 * * @paramaccount * @return */ public staticString getCache(String account) { account =getCacheKey(account); //如果缓冲中有该账号,则返回value if(cacheMap.containsKey(account)) { returncacheMap.get(account); } //如果缓存中没有该账号,把该帐号对象缓存到concurrentHashMap中 initCache(account); returncacheMap.get(account); } /*** 初始化缓存 * * @paramaccount */ private static voidinitCache(String account) { //一般是进行数据库查询,将查询的结果进行缓存 cacheMap.put(account, "18013093863"); } /*** 拼接一个缓存key * * @paramaccount * @return */ private staticString getCacheKey(String account) { return Thread.currentThread().getId() + "-" +account; } /*** 移除缓存信息 * * @paramaccount */ public static voidremoveCache(String account) { cacheMap.remove(getCacheKey(account)); } }