listener 监听器
package com.hbsc.listener;
import com.hbsc.domain.IndexUserBo;
import com.hbsc.domain.IndexUserVo;
import com.hbsc.util.UserUtil;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.stereotype.Component;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
@Component
@WebListener
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 180)
public class OnlinePeople implements HttpSessionListener {
private static Map<String, HttpSession> onLines=new HashMap<>();
public static synchronized Map<String, HttpSession> getOnLines() {
return onLines;
}
@Override
public void sessionCreated(HttpSessionEvent se) {
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// Map<String, HttpSession> onLines=(Map<String, HttpSession>) se.getSession().getServletContext().getAttribute("onLines");
HttpSession session=se.getSession();
if(OnlinePeople.getOnLines().containsKey(session.getId()))
{
IndexUserVo userVo= (IndexUserVo)session.getAttribute("user");
OnlinePeople.getOnLines().remove(session.getId());
System.out.println("一个用户下线了....移除了:"+"sessionId="+session.getId()+"And username="+ userVo.getUserName());
}
}
}
2.登录时录入
Map<String, HttpSession> onLines
登录代码
OnlinePeople.getOnLines().put(request.getSession().getId(),session);
3.踢人
session.invalidate();
重点
@Component //让spring容器管理
@WebListener//监听器注解
可以参考spring_boot实现监听器的4种方式