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包