我有一个HttpSession和ip的Map,在初始化请求时添加。它通常在会话被销毁时删除,但有时不会发生,我想手工完成。
如何从此地图中删除已经失效的会话?
监听
...
private static final Map<HttpSession, String> sessions = new ConcurrentHashMap<>();
@Override
public void requestInitialized(ServletRequestEvent ev) {
HttpServletRequest request = (HttpServletRequest) ev.getServletRequest();
HttpSession session = request.getSession();
if(session.isNew()){
sessions.put(session, request.getRemoteAddr());
}
}
@Override
public void sessionDestroyed(HttpSessionEvent ev) {
sessions.remove(ev.getSession());
}
...
答案 0 :(得分:0)
我试试这种方式似乎工作正常!
public static void cleanUpMemorySessions() {
sessions.entrySet().forEach((entry) -> {
try {
entry.getKey().isNew();
} catch(IllegalStateException e) {
sessions.remove(entry.getKey());
}
});
}