java中的map缓存

做项目涉及到了map缓存,记录一下:

public class MapCacheUtil {

    private static MapCacheUtil mapCache;
    private Map<Object, Object> cacheItems;

    private MapCacheUtil() {
        cacheItems = new ConcurrentHashMap<Object, Object>();
    }

    /**
     * 获取唯一实例
     * 
     * @return instance
     */
    public static MapCacheUtil getInstance() {
        if (mapCache == null) {
            synchronized (MapCacheUtil.class) {
                if (mapCache == null) {
                    mapCache = new MapCacheUtil();
                }
            }
        }
        return mapCache;
    }

    /**
     * 获取所有cache信息
     * 
     * @return cacheItems
     */
    public Map<Object, Object> getCacheItems() {
        return this.cacheItems;
    }

    /**
     * 清空cache
     */
    public void clearAllItems() {
        cacheItems.clear();
    }

    /**
     * 获取指定cache信息
     * 
     * @param key 唯一标识
     * @return Object cacheItem
     */
    public Object getCacheItem(Object key) {
        if (cacheItems.containsKey(key)) {
            return cacheItems.get(key);
        }
        return null;
    }

    /**
     * 存值
     * 
     * @param key 唯一标识
     * @param value 存放的值
     */
    public Boolean putCacheItem(Object key, Object value) {
        if (!cacheItems.containsKey(key)) {
            cacheItems.put(key, value);
            return true;
        }
        return false;
    }

    /**
     * 根据key删除
     * 
     * @param key 唯一标识
     */
    public void removeCacheItem(Object key) {
        if (cacheItems.containsKey(key)) {
            cacheItems.remove(key);
        }
    }

    /**
     * 获取cache长度
     * 
     * @return size
     */
    public int getSize() {
        return cacheItems.size();
    }
}

调用很简单:直接创建实例,调用putCacheItem把值存入缓存

        MapCacheUtil mapCacheUtil = MapCacheUtil.getInstance();
        Boolean cacheResult = mapCacheUtil.putCacheItem(roomId, videoUrl);

取也很简单,如下(根据key去取值)

        MapCacheUtil mapCacheUtil = MapCacheUtil.getInstance();
        String videoUrl = mapCacheUtil.getCacheItem(roomId).toString();

map缓存项目停止后,map缓存会被清除。

在一个项目下,一个servlet存,一个main方法取,结果取不到缓存中的值,有人告诉我是和main方法有关,我就把main方法换成servlet了,结果就取到了,但是现在还没想通是为啥,有知道能告知一下吗?

猜你喜欢

转载自blog.csdn.net/shuoshuo_12345/article/details/87192184