天天看點

Springboot 用session監聽器統計線上使用者數量

今天給大家分享這個吧。

利用Springboot中的session監聽器去實作統計線上使用者數量的需求(當然其實用shiro或者security是架構自己帶有會話管理的,用起來更加友善)。

但是, 接下來這個是非常簡單直接快速的實作這個需求,不廢話了

上代碼:

第一步  . 既然用監聽器實作,那肯定得建立監聽器了。 

建立SessionListener.class

我用的是最直接的注解方式,圖友善。   

這邊的關鍵是兩點,①@WebListener  ②implements HttpSessionListener

其他的思路看代碼就能看懂,而且也做了注釋。

import javax.servlet.annotation.WebListener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


/**
 * @Author : JCccc
 * @CreateTime : 2018-11-15
 * @Description :
 * @Point: Keep a good mood
 **/

@WebListener
public class SessionListener implements HttpSessionListener{

    private int onlineCount = 0;//記錄session的數量

    /**
     * session建立後執行
     */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        onlineCount++;
        System.out.println("【HttpSessionListener監聽器】 sessionCreated, onlineCount:" + onlineCount);
       //将最新的onlineCount值存起來
        se.getSession().getServletContext().setAttribute("onlineCount", onlineCount);

    }

    /**
     * session失效後執行
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        if (onlineCount > 0) {
            onlineCount--;
        }
        System.out.println("【HttpSessionListener監聽器】 sessionDestroyed, onlineCount:" + onlineCount);
        //将最新的onlineCount值存起來
        se.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
    }

}      

第二步. 好了其實已經完成了。

接下來就是單純的校驗:

首先模拟一個系統的登入接口,

@GetMapping("/login")
 public String login(HttpSession session){
    //模拟一個使用者調用了登入接口,進入系統
    return "使用者登入";
}      

然後在浏覽器通路一下,假裝登入:

Springboot 用session監聽器統計線上使用者數量

這時候,你可以看到控制台輸出了:

Springboot 用session監聽器統計線上使用者數量

是的,已經統計到一個了。

然後你可以繼續用浏覽器通路,你會發現控制台不會繼續輸出,因為你的ip對應的這個session還沒過期,這就避免了重複統計。

然後,你把你的這個/login丢給你身邊的小夥伴測試下,你就會發現控制台又輸出了,而且 onlineCount變成2了。

最後,再寫個擷取這個統計值 onlineCount吧:

@GetMapping("/getOnlineCount")
public String getOnlineCount(HttpServletRequest httpServletRequest){
    HttpSession  session = httpServletRequest.getSession();
    //将session監聽器的統計線上人數給拿出來~
    Object onlineCount=session.getServletContext().getAttribute("onlineCount");
    //展示一下,看看
    return "onlineCount : "+onlineCount;
}      

再貼一個圖,session過期了就會這樣~

Springboot 用session監聽器統計線上使用者數量

好了,就到此吧,順便一提,在監聽器那邊是可以每次統計之後,不止set進session裡面,還可以存資料庫。

繼續閱讀