ConcurrentHashMap进行缓存

  • Post author:
  • Post category:其他


import java.util.concurrent.ConcurrentHashMap;


public class ConcurrentHashMapTest {


    private static ConcurrentHashMap<String, String> cacheMap = new ConcurrentHashMap<>();


    /**
    * 获取缓存的对象
    * @param account
    * @return String
    */
    public static String getCache(String key,String value) {


        key = getCacheKey(key);
        // 如果缓冲中有该账号,则返回value
        if (cacheMap.containsKey(key)) {
        return cacheMap.get(key);
        }
        // 如果缓存中没有该账号,把该帐号对象缓存到concurrentHashMap中
        initCache(key,value);
        return cacheMap.get(key);
    }


    /**
    * 初始化缓存
    * @param key
    */
    private static void initCache(String key,String value) {
        // 一般是进行数据库查询,将查询的结果进行缓存
        cacheMap.put(key, value);
    }


    /**
    * 拼接一个缓存key
    * @param key
    */
    private static String getCacheKey(String key) {
        return Thread.currentThread().getId() + "-" + key;
    }


    /**
    * 移除缓存信息
    * @param key
    */
    public static void removeCache(String key) {
        cacheMap.remove(getCacheKey(key));
    }
}



版权声明:本文为u014785563原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。