How to get all sessions in Vaadin

后端 未结 2 1996
礼貌的吻别
礼貌的吻别 2021-01-11 23:03

I want to know How many users are connected to my application in real time. I got the idea to loop on number of session that are open but I can\'t find how to do that. If yo

2条回答
  •  [愿得一人]
    2021-01-11 23:49

    Best solution i found so far is to count the sessions when they are created and destroyed.

    public class VaadinSessionListener{
    
        private static volatile int activeSessions = 0;
    
        public static class VaadinSessionInitListener implements SessionInitListener{
    
            @Override
            public void sessionInit(SessionInitEvent event) throws ServiceException {
    
                incSessionCounter();            
            }
        }
    
        public static class VaadinSessionDestroyListener implements SessionDestroyListener{
    
            @Override
            public void sessionDestroy(SessionDestroyEvent event) {
    
                /*
                 * check if HTTP Session is closing
                 */
                if(event.getSession() != null && event.getSession().getSession() != null){
    
                    decSessionCounter();
                }
            }
        }
    
    
        public static Integer getActiveSessions() {
            return activeSessions;
        }
    
        private synchronized static void decSessionCounter(){
            if(activeSessions > 0){
                activeSessions--;
            }
        }
    
        private synchronized static void incSessionCounter(){
            activeSessions++;
        }
    }
    

    then add the SessionListeners in the VaadinServlet init() method

    @WebServlet(urlPatterns = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = true, ui = MyUI.class)
    public static class Servlet extends VaadinServlet {
    
        @Override
        public void init(ServletConfig servletConfig) throws ServletException {
    
            super.init(servletConfig);
    
    
            /*
             * Vaadin SessionListener
             */
            getService().addSessionInitListener(new VaadinSessionListener.VaadinSessionInitListener());
            getService().addSessionDestroyListener(new VaadinSessionListener.VaadinSessionDestroyListener());    
        }
    }
    

提交回复
热议问题