Home >Java >javaTutorial >How to implement the function of counting online people in Java

How to implement the function of counting online people in Java

WBOY
WBOYforward
2023-04-19 09:13:021861browse

    1. Introduction to the listener

    A listener is an ordinary Java program that implements a specific interface. This program is specially used to monitor another Java object. Method call or attribute change, when the above event occurs on the monitored object, a method of the listener will be executed immediately.

    2. Types of Java listeners

    (1)ServletContextListener

    Used to listen to WEB, application startup and destruction events

    public void contextInitialized( ServletContextEvent sce): Executed when initializing the web application

    public void contextDestroyed(ServletContextEvent sce) {}: Executed when destroying the web application

    (2)HttpSessionListener

    is used Monitor the creation and destruction of Session objects

    public void sessionCreated(HttpSessionEvent se) {}: Executed when the session is created

    public void sessionDestroyed(HttpSessionEvent se) {}: Executed when the session is destroyed

    (3)ServletRequestListener

    Used to monitor the creation and destruction of Requset objects

    public void requsetCreated(HttpSessionEvent se) {}:Executed when requset is created

    public void requestDestroyed(HttpSessionEvent se) {}: Executed when requset is destroyed

    (4)ServletContextAttributeListener

    is used to monitor changes in WEB scope attributes, including: adding attributes, deleting attributes Attributes, modify attributes

    attributeAdded(ServletContextEvent sce): Executed when adding attributes to ServletContext

    attributeAdded(ServletContextRemoved sce): Executed when deleting attributes from ServletContext

    attributeReplaced(ServletContextRemoved sce): Executed when modifying attributes in ServletContext

    (5)HttpSessionAttributeListener

    is used to monitor changes in Session scope attributes, including: adding attributes, deleting attributes, modifying attributes

    (6)ServletRequestAttributeListener

    is used to monitor changes in Requset scope attributes, including: adding attributes, deleting attributes, modifying attributes

    (7)HttpSessionActivationListener

    is used to listen Serialization and deserialization of an object in Session

    3. Listener implements the function of counting people

    (1) First create the listener package listener and then create a new OnlineListener class

    package listener;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    import javax.servlet.http.HttpSessionAttributeListener;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    import javax.servlet.http.HttpSessionBindingEvent;
     
    @WebListener()
    public class OnlineListener implements ServletContextListener,HttpSessionListener, HttpSessionAttributeListener {
    
        private static int count=0;
     
        public OnlineListener() {//构造函数
        }
     
        // ServletContextListener的实现方法,在初始化web应用时执行,你可以在此处初始化server上下文相关数据
        public void contextInitialized(ServletContextEvent sce) {//应用初始化完成
       
        }
       
        // ServletContextListener的实现方法,在web应用关闭时执行
        public void contextDestroyed(ServletContextEvent sce) {
         
        }
     
        // HttpSessionListener的实现方法,session被创建的时候执行
        public void sessionCreated(HttpSessionEvent se) {//创建
            count++;
            ServletContext app = se.getSession().getServletContext();
            app.setAttribute("count",count);
        }
    
    
       // HttpSessionListener的实现方法,session被销毁的时候执行
        public void sessionDestroyed(HttpSessionEvent se) {
            count--;
            ServletContext app = se.getSession().getServletContext();
            app.setAttribute("count",count);
        }
    }

    (2) Create the interface of the listener servlet

    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
     
    @WebServlet(name = "OnlineServlet",urlPatterns = "/online")
    public class OnlineServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         this.doGet(request, response);
        }
     
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          String op=request.getParameter("op");
          String result="";
          switch (op){
              case "login":
                  //request.getSession()触发监听器的sessionCreated
                  ServletContext app=request.getSession().getServletContext();
                  int count= (int) app.getAttribute("count");
                  result=String.format("当前%d人在线",count);
                  break;
              case "logout":
                  //销毁session,触发监听器的sessionDestroy
                  request.getSession().invalidate();//销毁session
                  result="您已经退出了!";
          }
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out=response.getWriter();
            out.write(result);
            out.close();
        }
    }

    4.Redis implements the function of counting people

    Requirements: average access time, average number of people online at the same time, and the highest number of people online at the same time

    (1) First design the data table:

    Start accessing the page time, leave the page timetable: (id, place, ip, user_id, user_name, begin_time, end_time, env, info, len_min)

    Statistical table: average visit duration, average number of people online at the same time, maximum number of people online at the same time (id, day, age_len_visit_min, acu, pcu)

    Statistical record table: number of people online at the same time per minute. (id, min_time, num)

    (2) Use redis to store the current online users. Each call can be regarded as browsing for one minute (it can be further refined according to the business, and only the scheduled task needs to record the last minute) and users in the current minute, you can calculate how often a user visits a certain page.

    (3) At the same time, record the time when the user starts visiting the page and the time when he leaves the page, and you can analyze the follow-up.

    (4) To facilitate data processing, the number of visits per page per minute can be recorded.

    (5) redis, stores 2 hashes:

    begin, timer The stored hash set records detailed information

    now, the user access set passed by the interface, and records the refresh time

    Update and refresh operations are performed through timers.

    ps: Individual keys in the hash cannot be automatically set to expire, or you can use redis monitoring and use String type keys. Monitoring is filtering, and you can process what you need to process after matching it.

    The above is the detailed content of How to implement the function of counting online people in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete