zoukankan      html  css  js  c++  java
  • 简单的Map缓存机制实现

    简单的Map缓存机制实现

    大致思路是用一个单例的Map实现,当然此Map得是线程安全的--ConcurrentHashMap

    原本项目需求是缓存十条消息,所以打算用Map实现缓存机制。中途夭折下面具体尚未实现。。。

    当然此代码仞为半成品,具体得根据项目需求采用不同的原则清除缓存

    package per.zww.util;
    
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    
    public class CachePool {
        private static CachePool cachePool;
        private Map<Object, Object> cacheItems;
        private CachePool() {
            cacheItems =new ConcurrentHashMap<Object, Object>();
        }
        /**
         * 获取唯一实例
         * @return instance
         */
        public static CachePool getInstance() {
            if (cachePool ==null) {
                synchronized (CachePool.class) {
                    if (cachePool ==null) {
                        cachePool =new CachePool();
                    }
                }
            }
            return cachePool;
        }
        
        /**
         * 获取所有cache信息
         * @return cacheItems
         */
        public Map<Object, Object> getCacheItems() {
            return this.cacheItems;
        }
        
        /**
         * 清空cache
         */
        public void clearAllItems() {
            cacheItems.clear();
        }
        
        /**
         * 获取指定cache信息
         * @return cacheItem
         */
        public Object getCacheItem(Object key) {
            if (cacheItems.containsKey(key)) {
                return cacheItems.get(key);
            }
            return null;
        }
        
        /**
         * 存放cache信息
         */
        public void putCacheItem(Object key,Object value) {
            if (!cacheItems.containsKey(key)) {
                cacheItems.put(key, value);
            }
        }
        
        /**
         * 删除一个cache
         */
        public void removeCacheItem(Object key) {
            if (cacheItems.containsKey(key)) {
                cacheItems.remove(key);
            }
        }
        
        /**
         * 获取cache长度
         * @return size
         */
        public int getSize() {
            return cacheItems.size();
        }
        
    }
  • 相关阅读:
    vue封装一些常用组件loading、switch、progress
    个人推荐的两款vue导出EXCEL插件
    解决react项目中跨域和axios封装使用
    vue仿阿里云后台管理(附加阿里巴巴图标使用)
    简单的利用nginx部署前端项目
    Python3 SMTP发送邮件
    WINDOWS和UNIX换行符的理解
    Forward Proxy vs Reverse Proxy
    Authentication token is no longer valid
    SNMP Introduction
  • 原文地址:https://www.cnblogs.com/zhaoww/p/5122969.html
Copyright © 2011-2022 走看看