cookie和session-自定义缓存类

缓存实体类:

public class Cache {
public Cache(String key, Object value, Long timeOut) {
		super();
		this.key = key;
		this.value = value;
		this.timeOut = timeOut;
	}
public Cache() {

}
	/**
	 * key
	 */
	private String key;
	/**
	 * 缓存数据
	 */
	private Object value;
	/**
	 * 超时时间
	 */
	private Long timeOut;

	public String getKey() {

		return key;
	}

	public void setKey(String key) {

		this.key = key;
	}

	public Object getValue() {

		return value;
	}

	public void setValue(Object value) {

		this.value = value;
	}

	public Long getTimeOut() {

		return timeOut;
	}

	public void setTimeOut(Long timeOut) {

		this.timeOut = timeOut;
	}
}

缓存类:

/**
 * 
 * @classDesc: 功能描述:(缓存map)
 */
public class CacheManager {

	private Map<String, Cache> cacheMap = new HashMap<>();

	/**
	 * 
	 * @methodDesc: 功能描述:(往缓存存值)
	 */
	public void put(String key, Object oj) {
		put(key, oj, null);
	}

	/**
	 * 
	 * @methodDesc: 功能描述:(往缓存存值)
	 */
	public synchronized void put(String key, Object oj, Long timeOut) {
		if (oj == null) {
			return;
		}
		Cache cache = new Cache();
		cache.setKey(key);
		if (timeOut != null)
			cache.setTimeOut(timeOut + System.currentTimeMillis());
		cache.setValue(oj);
		cacheMap.put(key, cache);
	}

	/**
	 * 
	 * @methodDesc: 功能描述:(删除)
	 */
	public synchronized void deleteCache(String key) {
		cacheMap.remove(key);
	}

	/**
	 * 
	 * @methodDesc: 功能描述:(获取缓存中数据)
	 */
	public synchronized Object get(String key) {
		Cache cache = cacheMap.get(key);
		Object oj = null;
		if (cache != null) {
			oj = cache.getValue();
		}
		return oj;
	}

	/**
	 * 
	 * @methodDesc: 功能描述:(检查数据是否在有效期内)
	 */
	public synchronized void checkValidityData() {
		for (String key : cacheMap.keySet()) {
			Cache cache = cacheMap.get(key);
			Long timeOut = cache.getTimeOut();
			if (timeOut == null) {
				return;
			}
			long currentTime = System.currentTimeMillis();
			long endTime = timeOut;
			long result = (currentTime - endTime);
			if (result > 0) {
				System.out.println("清除:"+key);
				cacheMap.remove(key);
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		CacheManager cacheManager = new CacheManager();
		// cacheManager.put("lisi", 0);
		cacheManager.put("zhangsan", "jj", 5000l);
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
		scheduledThreadPool.schedule(new Runnable() {
			public void run() {
				cacheManager.checkValidityData();
			}
		}, 5000, TimeUnit.MILLISECONDS);
		Thread.sleep(5000);
		System.out.println(cacheManager.get("zhangsan"));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值