package com.cweb.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionKeyCache {
	
	private static Map<String, CacheData> CACHE_DATA = new ConcurrentHashMap<>();

	public static <T> T getData(String key) {
		CacheData<T> data = CACHE_DATA.get(key);
		if (data != null){
			if(data.getExpire() <= 0 || data.getSaveTime() >= System.currentTimeMillis()) {
				 return data.getData();
			}else{
				clear(key);
			}
		}
		return null;
	}

	public static <T> void setData(String key, T data, int expire) {
		CACHE_DATA.put(key, new CacheData(data, expire));
	}

	public static void clear(String key) {
		CACHE_DATA.remove(key);
	}

	private static class CacheData<T> {
		CacheData(T t, int expire) {
			this.data = t;
			this.expire = expire <= 0 ? 0 : expire*1000;
			this.saveTime = System.currentTimeMillis() + this.expire;
		}

		private T data;
		private long saveTime; // 存活时间
		private long expire; // 过期时间 小于等于0标识永久存活

		public T getData() {
			return data;
		}

		public long getExpire() {
			return expire;
		}

		public long getSaveTime() {
			return saveTime;
		}
	}
}
