首页

关于hessian基于ConcurrentHashMap堆内存的缓存实现CaptchaCache源码说明分享

标签:缓存原理,hessian,堆内存缓存,ConcurrentHashMap,CaptchaCache,自定义缓存     发布时间:2018-02-07   

一、前言

对于缓存cache大家并不陌生,像分布式缓存memecacheredis、google的guava的cache等,这边基于hessian的CaptchaCache通过java.util.concurrent.ConcurrentHashMap、java.util.Timer自定义实现简单的缓存,具体源码如下所示

二、源码说明

package com.jfinal.captcha;@b@@b@import java.util.Map.Entry;@b@import java.util.Timer;@b@import java.util.TimerTask;@b@import java.util.concurrent.ConcurrentHashMap;@b@@b@/**@b@ * ICaptchaCache 默认实现,可用于单实例部署@b@ * 集群部署需自行实现 ICaptchaCache 接口,并使用@b@ * CaptchaManager.setCaptchaCache(...) 进行配置@b@ */@b@public class CaptchaCache implements ICaptchaCache {@b@	@b@	private ConcurrentHashMap<String, Captcha> map = new ConcurrentHashMap<String, Captcha>();@b@	private int interval = 90 * 1000;	// timer 调度间隔为 90 秒@b@	private Timer timer;@b@	@b@	public CaptchaCache() {@b@		autoRemoveExpiredCaptcha();@b@	}@b@	@b@	/**@b@	 * 定期移除过期的验证码@b@	 */@b@	private void autoRemoveExpiredCaptcha() {@b@		timer = new Timer("CaptchaCache", true);@b@		timer.schedule(@b@			new TimerTask() {@b@				public void run() {@b@					for (Entry<String, Captcha> e : map.entrySet()) {@b@						if (e.getValue().isExpired()) {@b@							map.remove(e.getKey());@b@						}@b@					}@b@				}@b@			},@b@			interval,@b@			interval@b@		);@b@	}@b@	@b@	public void put(Captcha captcha) {@b@		map.put(captcha.getKey(), captcha);@b@	}@b@	@b@	public Captcha get(String key) {@b@		return key != null ? map.get(key) : null;@b@	}@b@	@b@	public void remove(String key) {@b@		map.remove(key);@b@	}@b@	@b@	public void removeAll() {@b@		map.clear();@b@	}@b@	@b@	public boolean contains(String key) {@b@		return map.containsKey(key);@b@	}@b@}