您的位置:首页 > 编程语言 > Java开发

java对象本地缓存机制的实现

2014-11-29 17:30 686 查看
本地缓存机制,利用java.util.concurrent,很好的管理本地内存存储的对象内容。

创建属性:

 /**

     * 具体内容存放的地方

     */

    private ConcurrentHashMap<String, Object>[] caches;

    /**

     * 超期信息存储

     */

    private ConcurrentHashMap<String, Long> expiryCache;

    /**

     * 清理超期内容的服务

     */

    private ScheduledExecutorService scheduleService;

    /**

     * 清理超期信息的时间间隔,默认10分钟

     */

    private int expiryInterval = 5;

    /**

     * 内部cache的个数,根据key的hash对module取模来定位到具体的某一个内部的Map,

     */

    private int moduleSize = 10;

创建构造器:    

  public MyLocalCache() {

        caches = new ConcurrentHashMap[moduleSize];

        for (int i = 0; i < moduleSize; i++) {

            caches[i] = new ConcurrentHashMap<String, Object>();

        }

        expiryCache = new ConcurrentHashMap<String, Long>();

        scheduleService = Executors.newScheduledThreadPool(1);

        //后台定时维护线程

        scheduleService.scheduleAtFixedRate(getRemoveLocalCacheTask(), 0, 60L * expiryInterval, TimeUnit.SECONDS);

    }

定义缓存的get和put方法:

  /**

     * 将数据放入缓存中

     * @param key

     * @param value

     * @param TTL 秒

     * @return

     */

    public Object put(String key, Object value, int TTL) {

        Object result = null;

        ConcurrentHashMap<String, Object> cache = getCache(key);

        if (cache != null && cache.size() < 10240) {

            result = cache.put(key, value);

            Calendar calendar = Calendar.getInstance();

            calendar.add(Calendar.SECOND, TTL);

            expiryCache.put(key, calendar.getTime().getTime());

        }

        return result;

    }

    public Object get(String key) {

        checkValidate(key);

        return getCache(key).get(key);

    }

//根据key获取cache容器

    private ConcurrentHashMap<String, Object> getCache(String key) {

        long hashCode = (long) key.hashCode();

        if (hashCode < 0) {

            hashCode = -hashCode;

        }

        int moudleNum = (int) (hashCode % moduleSize);

        return caches[moudleNum];

    }

校验key是否过期,如果过期了,就要移除

 private void checkValidate(String key) {

        if (key != null) {

            Long expiryTime = expiryCache.get(key);

            if (expiryTime != null && expiryTime != -1

                    && new Date(expiryTime).before(new Date())) {

                ConcurrentHashMap<String, Object> cache = getCache(key);

                if (cache != null) {

                    cache.remove(key);

                }

                expiryCache.remove(key);

            }

        }

    }

清除所有的缓存:    key和内容  全部清空

 public boolean clear() {

        if (caches != null) {

            for (ConcurrentHashMap<String, Object> cache : caches) {

                cache.clear();

            }

        }

        if (expiryCache != null) {

            expiryCache.clear();

        }

        return true;

    }

定时器:  检查过期内容

 public Runnable getRemoveLocalCacheTask() {

        return new Runnable() {

            @Override

            public void run() {

                try {

                    for (ConcurrentHashMap<String, Object> cache : caches) {

                        Iterator<String> keys = cache.keySet().iterator();

                        while (keys.hasNext()) {

                            String key = keys.next();

                            if (expiryCache.get(key) == null) {

                                continue;

                            }

                            long date = expiryCache.get(key);

                            if ((date > 0) && (new Date(date).before(new Date()))) {

                                expiryCache.remove(key);

                                cache.remove(key);

                            }

                        }

                    }

                    logger.debug("MingpinLocalCache CheckService check() is run!");

                } catch (Exception ex) {

                    logger.error(ex);

                }

            }

        };

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  缓存机制 存储 cache