统计当前在线人数

当一个项目启动时,要统计当前在线人数,那么我们可以统计一个当前有几个session登录,增加一个session,表明已经有新浏览器访问该网站。实现

HttpSessionListener, HttpSessionAttributeListener,覆盖其方法。
public class UsersListener implements HttpSessionListener, HttpSessionAttributeListener {
    
    private ServletContext sc;
    //使用一个变量,进行统计
    private int count = 0;
    
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        
        if( sc == null)
            sc = event.getSession().getServletContext();
        
        sc.setAttribute(Constants.SESSION_COUNT, count);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        Enumeration<String> names = event.getSession().getAttributeNames();
        int line = 0;
        while(names.hasMoreElements()) {
            String name = names.nextElement();
            //统计剩余几个用户
if(name.equalsIgnoreCase(Constants.FRONT_USER_SESSION)) {
                line ++;
            }
        }
        if(line > 0) {
            count = line;
        }
        if(sc != null)
            sc.setAttribute(Constants.SESSION_COUNT, count);
    }
        //新增session
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        String name = event.getName();
        if(name.equalsIgnoreCase(Constants.FRONT_USER_SESSION))
            count ++;
        sc.setAttribute(Constants.SESSION_COUNT, count);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        String name = event.getName();
        if(count > 0 && name.equalsIgnoreCase(Constants.FRONT_USER_SESSION))
            count --;
        sc.setAttribute(Constants.SESSION_COUNT, count);
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        
    }
    
}

 

你可能感兴趣的:(统计当前在线人数)