今天重看張孝祥(緬懷你)的ThreadLocal線程範圍內共享變量的視頻時,在最後提到了,當一個線程快要死亡時,可以通過監聽器得到通知。還有在面試中遇到統計在線人數的實現,利用session過期添加監控器得到通知。
session的監聽
監聽session主要有三個接口,用這兩個就夠用了。
實現接口HttpSessionListener下的sessionCreated();//當session創建時。
和sessionDestroyed();//當session被銷燬或超時時。
實現接口HttpSessionAttributeListener下的 attributeAdded() //當給session添加屬性時
attributeRemoved();和attributeReplaced();
以下是簡單的實現了在線人數統計的功能。
@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener{
public static final Logger logger= LoggerFactory.getLogger(SessionListener.class);
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
logger.info("--attributeAdded--");
HttpSession session=httpSessionBindingEvent.getSession();
logger.info("key----:"+httpSessionBindingEvent.getName());
logger.info("value---:"+httpSessionBindingEvent.getValue());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
logger.info("--attributeRemoved--");
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
logger.info("--attributeReplaced--");
}
@Override
public void sessionCreated(HttpSessionEvent event) {
logger.info("---sessionCreated----");
HttpSession session = event.getSession();
ServletContext application = session.getServletContext();
// 在application範圍由一個HashSet集保存所有的session
HashSet sessions = (HashSet) application.getAttribute("sessions");
if (sessions == null) {
sessions = new HashSet();
application.setAttribute("sessions", sessions);
}
// 新創建的session均添加到HashSet集中
sessions.add(session);
// 可以在別處從application範圍中取出sessions集合
// 然後使用sessions.size()獲取當前活動的session數,即爲“在線人數”
}
@Override
public void sessionDestroyed(HttpSessionEvent event) throws ClassCastException {
logger.info("---sessionDestroyed----");
HttpSession session = event.getSession();
logger.info("deletedSessionId: "+session.getId());
System.out.println(session.getCreationTime());
System.out.println(session.getLastAccessedTime());
ServletContext application = session.getServletContext();
HashSet sessions = (HashSet) application.getAttribute("sessions");
// 銷燬的session均從HashSet集中移除
sessions.remove(session);
}
}