基于Map多种方式实现简单的缓存处理
通过HashMap进行缓存
private static Map<String, Object> cacheMap; public static Object getCache(String key, Object defaultValue) { Object obj = getCacheMap().get(key); //Object obj = getSession().getAttribute(key); return obj==null?defaultValue:obj; } public static void putCache(String key, Object value) { getCacheMap().put(key, value); //getSession().setAttribute(key, value); } public static void removeCache(String key) { getCacheMap().remove(key); //getSession().removeAttribute(key); } public static Map<String, Object> getCacheMap() { if (cacheMap==null){ cacheMap = new HashMap<String, Object>(); } return cacheMap; }
通过 LinkedHashMap实现:
/** * 使用的是LinkedHashMap实现 */ public class LRU<K, V> extends LinkedHashMap<K, V> { private static final long serialVersionUID = 1L; //缓存大小 private int cachaSize; public LRU(int cachaSize) { 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()); } return r; } }
ConcurrentHashMap的本地缓存实现:与Guava cache相比,ConcurrentHashMap需要自己显式的删除缓存
import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapTest { private static ConcurrentHashMap<String, String> cacheMap = new ConcurrentHashMap<>(); /** * 获取缓存的对象 * * @param account * @return */ public static String getCache(String account) { account = getCacheKey(account); // 如果缓冲中有该账号,则返回value if (cacheMap.containsKey(account)) { return cacheMap.get(account); } // 如果缓存中没有该账号,把该帐号对象缓存到concurrentHashMap中 initCache(account); return cacheMap.get(account); } /** * 初始化缓存 * * @param account */ private static void initCache(String account) { // 一般是进行数据库查询,将查询的结果进行缓存 cacheMap.put(account, "18013093863"); } /** * 拼接一个缓存key * * @param account * @return */ private static String getCacheKey(String account) { return Thread.currentThread().getId() + "-" + account; } /** * 移除缓存信息 * * @param account */ public static void removeCache(String account) { cacheMap.remove(getCacheKey(account)); } }