Springboot uses a listener to collect statistics on the number of online users. Case study: springboot listeners

Source: Internet
Author: User

Springboot uses a listener to collect statistics on the number of online users. Case study: springboot listeners

In the springboot project, this article uses the HttpSessionListener listener (one of the listeners) to count the number of online users. In essence, it is used to count the number of sessions.

The idea is very simple, but the details are not well handled. It took me a long time to debug the bug.

First, write an HttpSessionListener listener. Count is the number of sessions. When a session is created, the sessionCreated method of the listener is triggered. When the session is destroyed, the sessionDestroyed method of the listener is triggered. Calculate the count in the listener and put it into the servletContext (it can be understood as a warehouse, and any request can store and obtain the attributes in it ).
Pay attention to adding @ WebListener to the listener so that no configuration is required.

@ WebListener public class OnLineCount implements HttpSessionListener {public int count = 0; // record the number of sessions // listen to the creation of sessions, and the synchronized defense concurrency bug public synchronized void sessionCreated (HttpSessionEvent arg0) {System. out. println ("[HttpSessionListener listener] count ++ Add"); count ++; arg0.getSession (). getServletContext (). setAttribute ("count", count) ;}@ Override public synchronized void sessionDestroyed (HttpSessionEvent arg0) {// listens to the session revocation System. out. println ("[HttpSessionListener listener] count -- decrease"); count --; arg0.getSession (). getServletContext (). setAttribute ("count", count );}}

Then I wrote a controller to query the number of sessions. It was wrong when I started writing like below!

Retrieve count from servletContext and return count to the front-end.

@RequestMapping("/count") @ResponseBody public String count(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){   Object count=httpServletRequest.getServletContext().getAttribute("count");   return "count : "+count; } 

This is an error. During the test, you will find that the count value on the page is null because no session is created and no statistical method is used to trigger the listener. So let's change it:

@Controller public class IndexController {   @RequestMapping("/count")   @ResponseBody   public String count(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){     HttpSession session = httpServletRequest.getSession();     Object count=session.getServletContext().getAttribute("count");     return "count : "+count;   } } 

HttpSession session = httpServletRequest. getSession (); function: If this user does not have sesision, the session is created. If yes, the session is obtained and not created.

This test seems correct, but there is a problem. A browser corresponds to a session. You can open two browsers and see that count is 2, which is correct. But when you close a browser and open it again, it should be 2, but it turns to 3, because the session destruction method is not executed, the server could not find the user's original session and re-created a session, so there were three sessions, but there were only two browsers, that is, the simulation should be that there were only two people online.

There are two ways to solve this problem. One is to call a method to destroy the session when the webpage is closed. Another better way is to let the server remember the original session, that is, record the original sessionId in the browser, and send the sessionId next time, so that the server will not be re-created.

The code is modified as follows:

@ Controller public class IndexController {@ RequestMapping ("/count") @ ResponseBody public String number (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {try {// record the sessionId in the browser Cookie c = new Cookie ("JSESSIONID", URLEncoder. encode (httpServletRequest. getSession (). getId (), "UTF-8"); c. setPath ("/"); // set the cookie validity period to 2 days. Do not worry, the session will not be saved for 2 days. setMaxAge (48*60*60); httpServletResponse. addCookie (c);} catch (Exception e) {e. printStackTrace ();} HttpSession session = httpServletRequest. getSession (); Object count = session. getServletContext (). getAttribute ("count"); return "count:" + count ;}}

Summary

The above is a case study on how to use a listener to count the number of online users in springboot. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.