Java之简易key过期管理器

简易key过期管理器,不想为了这点小功能去使用redis;

 

思路:key过期管理器,重点就在自动删除过期的key,我不想用定时任务或者创建一根线程定时去维护key,可以用事件驱动去删除过期的key,当校验key是否存在和存放新的过期key时会触发清理过期key的操作;

 

代码如下所示:

    // key-过期时间
    private static ConcurrentHashMap<String, LocalDateTime> expiredKeyMap = new ConcurrentHashMap<>(10);

    /**
     * 方法描述:设置key的过期时间
     * @param key       key
     * @param second    存活时间(秒)
     */
    public static void putExpiredKey(String key, long second) {
        clearExpiredKey();
        LocalDateTime expiredDate = LocalDateTime.now().plusSeconds(second);
        expiredKeyMap.put(key, expiredDate);
    }

    /**
     * 方法描述:key是否存活
     * @param key
     * @return
     */
    public static boolean isExist(String key) {
        if(expiredKeyMap.isEmpty()) {
            return false;
        }
        clearExpiredKey();
        return expiredKeyMap.containsKey(key);
    }

    /**
     * 方法描述:清理过期的key
     */
    private static void clearExpiredKey() {
        LocalDateTime now = LocalDateTime.now();
        Iterator<Map.Entry<String, LocalDateTime>> iterator = expiredKeyMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, LocalDateTime> next = iterator.next();
            LocalDateTime expiredDate = next.getValue();
            // 过期时间等于当前时间 或者 过期时间在当前时间之前
            if(now.equals(expiredDate) || now.isAfter(expiredDate)) {
                iterator.remove();
            }
        }
    }

 

调用代码:

        // 校验key是否存在
        boolean flag = CacheManager.isExist("key");
        // key不存在
        if(!flag) {
            //  设置5秒过期的key
            CacheManager.putExpiredKey("key", 5);
        }    

 

posted @ 2021-04-26 14:50  尘世间迷茫的小书童  阅读(333)  评论(0编辑  收藏  举报