package com.nbclass.util;

import java.util.Calendar;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

/**
 * 内存缓存工具类
 * @author Leon
 * @datetime 2020年6月19日 下午8:47:44
 */
public class MemoryCacheUtil {
	
	// 缓存map
    private static Map<String, Object> cacheMap = new ConcurrentHashMap<String, Object>();
    
    // 缓存有效期map
    private static Map<String, Long> expireTimeMap = new ConcurrentHashMap<String, Long>();
 
	/**
	 * 启动定时任务清理过期缓存，避免内存溢出
	 */
	static {
		Timer t = new Timer();
		t.schedule(new ClearTimerTask(cacheMap, expireTimeMap), 0, 60 * 1000);
	}
 
    /**
     * 获取指定的value，如果key不存在或者已过期，则返回null
     * @param key
     * @return
     */
    public static Object get(String key) {
        if (!cacheMap.containsKey(key)) {
            return null;
        }
        if (expireTimeMap.containsKey(key)) {
            if (expireTimeMap.get(key) < System.currentTimeMillis()) { // 缓存失效，已过期
            	cacheMap.remove(key);
            	expireTimeMap.remove(key);
            	return null;
            }
        }
        return cacheMap.get(key);
    }
 
    /**
     * 根据Key获取实体类，强转
     * @param key
     * @return
     */
	@SuppressWarnings("unchecked")
	public static <T> T getT(String key) {
        Object obj = get(key);
        return obj == null ? null : (T) obj;
    }
 
    /**
     * 设置value（不过期）
     * @param key
     * @param value
     */
    public static void set(String key, Object value) {
        cacheMap.put(key, value);
    }
 
    /**
     * 设置value
     * @param key
     * @param value
     * @param millSeconds 过期时间（毫秒）
     */
    public static void set(final String key, Object value, long millSeconds) {
        final long expireTime = System.currentTimeMillis() + millSeconds;
        cacheMap.put(key, value);
        expireTimeMap.put(key, expireTime);
        
        /*
        if(cacheMap.size() > 2){ // 清除过期数据
            new Thread(new Runnable() {
                public void run() {
                    // 此处若使用foreach进行循环遍历，删除过期数据，会抛出java.util.ConcurrentModificationException异常
                    Iterator<Map.Entry<String, Object>> iterator = cacheMap.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, Object> entry = iterator.next();
                        if (expireTimeMap.containsKey(entry.getKey())) {
                            long expireTime = expireTimeMap.get(key);
                            if (System.currentTimeMillis() > expireTime) {
                                iterator.remove();
                                expireTimeMap.remove(entry.getKey());
                            }
                        }
                    }
                }
            }).start();
        }
        */
    }
 
    /**
     * key是否存在
     * @param key
     * @return
     */
    public static boolean isExist(String key) {
    	if(StringUtils.isBlank(key))return false;
        return cacheMap.containsKey(key);
    }
    
	/**
	 * 移除指定key缓存
	 * @param key
	 */
	public static void remove(String key) {
		if(StringUtils.isBlank(key))return;
		cacheMap.remove(key);
		expireTimeMap.remove(key);
	}
	
	/**
	 * 移除所有缓存
	 */
	public static void removeAll() {
		cacheMap.clear();
		expireTimeMap.clear();
	}
	
    /**
     * 清理过期数据定时任务
     * @author Leon
     * @datetime 2020年6月5日 上午11:15:33
     */
	private static class ClearTimerTask extends TimerTask {
		
		Map<String, Object> cacheMap;
		
		Map<String, Long> expireTimeMap;
		
		public ClearTimerTask(Map<String, Object> cacheMap, Map<String, Long> expireTimeMap) {
			this.cacheMap = cacheMap;
			this.expireTimeMap = expireTimeMap;
		}
		
		@Override
		public void run() {
			Set<String> keys = cacheMap.keySet();
			for(String key : keys) {
				Long expireTime = expireTimeMap.get(key);
				if(expireTime == null || expireTime <= 0) {
					continue;
				}
				if(expireTime > Calendar.getInstance().getTimeInMillis()) {
					continue;
				}
				cacheMap.remove(key);
            	expireTimeMap.remove(key);
			}
		}
	}
 
    public static void main(String[] args) {
        MemoryCacheUtil.set("testKey_1", "testValue_1");
        MemoryCacheUtil.set("testKey_2", "testValue_2", 1);
        MemoryCacheUtil.set("testKey_3", "testValue_3");
        MemoryCacheUtil.set("testKey_4", "testValue_4", 1);
        Object testKey_2 = MemoryCacheUtil.get("testKey_2");
        System.out.println(testKey_2);
    }

}
