自定義session掃描器精確控制session銷毀時間--學習筆記
阿新 • • 發佈:2018-04-20
自定義session掃描器精確控制ses
package cn.xijie.listener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//HttpSession掃描器
public class SessionScanner implements ServletContextListener,HttpSessionListener{
private List<HttpSession> sessionList = new ArrayList<HttpSession>();
//線程安全
private Timer timer = new Timer();
public SessionScanner(){
//將線程不安全的List轉換成線程安全的List
sessionList = Collections.synchronizedList(sessionList);
}
//ServletContext產生
public void contextInitialized(ServletContextEvent sce) {
timer.schedule(new SessionTask(this.sessionList),0,1*1000);
}
//HttpSession產生
public void sessionCreated(HttpSessionEvent se) {
//取得客戶端產生的HttpSession
HttpSession session = se.getSession();
System.out.println("HttpSession產生" + session.hashCode() + new Date().toLocaleString());
synchronized (sessionList) {
//將HttpSession加入到容器中
this.sessionList.add(session);
}
}
//ServletContext銷毀
public void contextDestroyed(ServletContextEvent sce) {
timer.cancel();
}
//HttpSession銷毀
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
System.out.println("HttpSession銷毀" + session.hashCode() + new Date().toLocaleString());
}
}
//任務類
class SessionTask extends TimerTask{
private List<HttpSession> sessionList;
public SessionTask(List<HttpSession> sessionList) {
this.sessionList = sessionList;
}
public void run() {
System.out.println("run()");
//叠代集合
//Iterator<HttpSession> it = sessionList.iterator();
synchronized (sessionList) {
ListIterator<HttpSession> it = sessionList.listIterator();
while (it.hasNext()) {
HttpSession session = it.next();
//判段HttpSession是否1分鐘未被使用
int middle = (int) ((System.currentTimeMillis() - session
.getLastAccessedTime()) / 1000);
if (middle > 60) {
//將該HttpSession銷毀
session.invalidate();
//從集合中刪除該HttpSession ....有可能出現並發問題
//sessionList.remove(session);
it.remove();
}
}
}
}
}
run()
HttpSession產生6027721002018-4-20 14:47:32
run()
)
run()
run()
run()
HttpSession銷毀6027721002018-4-20 14:48:45
run()
自定義session掃描器精確控制session銷毀時間--學習筆記