配置web.xml:注意位置
<!-- 清理map缓存 --> <listener> <listener-class>com.test.utils.sms.CacheMap</listener-class> </listener>
监听类:
import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.test.utils.sms.VerifyCodeManager.InnerCode; public class CacheMap implements ServletContextListener { public void contextDestroyed(ServletContextEvent event) { // 服务停止时执行 } public void contextInitialized(ServletContextEvent arg0) { // 服务启动、初始化时执行------60分钟一次 int minutes = 60; int second = 60; int timeDistance = 1000; // 使用定时类,每隔一段时间执行 java.util.Timer timer = new java.util.Timer(); timer.schedule(new MyRandomMap(), new Date(), minutes * second * timeDistance); } private class MyRandomMap extends java.util.TimerTask // 实现了TimerTask的类 { public void run() { clearRandomMap();// 每隔一段时间执行 //System.out.println("start++++++++++"); } } public void clearRandomMap() { // 清除map过期的key List<String> list = new ArrayList<String>(); Iterator<String> iter = VerifyCodeManager.codes.keySet().iterator(); while (iter.hasNext()) { String key = iter.next().toString(); InnerCode val = VerifyCodeManager.codes.get(key); // 设计很巧妙:使用时间比较大小返回真假(取反),写入将要删除的数组 if (!val.isExpire()) { list.add(key); //System.out.println("key:"+key); } } // 执行删除操作 for (int i = 0; i < list.size(); i++) { VerifyCodeManager.codes.remove(list.get(i)); //System.out.println("delete:"+list.get(i)); } } }