listener监听事件
package listener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import java.util.concurrent.atomic.AtomicInteger; /** * 监听在线人数 * @author xuemeng * @date 2019/5/9 14:53 */ public class MySessionListener implements HttpSessionListener { //初始在线人数为0 public static AtomicInteger userCount = new AtomicInteger(0); /** * 用户登录,创建session会话,获得当前用户登录数+1 * @param httpSessionEvent */ @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) { userCount.getAndIncrement(); } /** * 用户退出,创建session会话,获得当前用户登录数-1 * @param httpSessionEvent */ @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { userCount.getAndDecrement(); } }
监听事件注册
package config; import com.gsww.iscs.apis.listener.MySessionListener; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author xuemeng * @date 2019/5/9 15:04 */ @Configuration public class SpringMvcConfig implements WebMvcConfigurer { @Bean public ServletListenerRegistrationBean getListener() { ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean(); servletListenerRegistrationBean.setListener(new MySessionListener()); return servletListenerRegistrationBean; } }
获取监听到得到数据
@Override public int getOnLineUser() { int count=0; //获取session AtomicInteger userCount = MySessionListener.userCount; count=(Integer.parseInt(userCount+"")); return count; }
*注意:一定是web项目,需要在pom中引入web包