springboot項目中整合Lislietener。動態獲取數據

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包

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章