Cache de mapas em java

O projeto envolve cache de mapa, registro:

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();
    }
}

A chamada é muito simples: crie uma instância diretamente, chame putCacheItem para armazenar o valor no cache

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

A busca também é muito simples, como segue (buscar o valor de acordo com a chave)

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

Depois que o projeto do cache do mapa for interrompido, o cache do mapa será limpo.

Em um projeto, um servlet é armazenado e um método principal é obtido. O resultado não pode ser obtido do valor no cache. Alguém me disse que está relacionado ao método principal. Substituí o método principal por um servlet e o resultado foi obtido, mas ainda não descobri por quê. Você pode me dizer se sabe?

Acho que você gosta

Origin blog.csdn.net/shuoshuo_12345/article/details/87192184
Recomendado
Clasificación