欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot 监听项目在线用户数

程序员文章站 2022-12-20 13:51:45
因为我们一般在用户登录系统或者网站后,会获取一个Session保证拦截器正常通过,所以一般可以采用监听器来监听项目创建Session的个数,在SpringBoot中提供了监听Session的方法,我们可以直接使用SpringBoot session监听方法统计用户在线数目的:获取Session数就能知道用户在线数(还未失效的用户数)具体实现步骤加入Session监听器1.实现HttpSessionListener接口中的两个方法注意需要在实现类加上@WebListener 注解,并实现下面两个方法...

因为我们一般在用户登录系统或者网站后,会获取一个Session保证拦截器正常通过,所以一般可以采用监听器来监听项目创建Session的个数,在SpringBoot中提供了监听Session的方法,我们可以直接使用

SpringBoot session监听方法统计用户在线数

目的:获取Session数就能知道用户在线数(还未失效的用户数)

具体实现步骤加入Session监听器

1.实现HttpSessionListener接口中的两个方法
注意需要在实现类加上@WebListener 注解,并实现下面两个方法
1.sessionCreated
1.1.在sessionCreated中进行总数++
2.sessionDestroyed
2.1在sessionDestroyed中进行总数–

注意在项目启动入口加上需要加上@ServletComponentScan //扫描监听器

注意事项:需要在项目启动入口加上注解:
@ServletComponentScan //扫描监听器
在SessionListe 上加上@WebListener 注解

具体实例

@WebListener
public class SessionListener implements HttpSessionListener {

    private Logger log = LoggerFactory.getLogger(SessionListener.class); //启动日志

    public static long onlineUserCount = 0;//在线人数

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        log.info("进入Session创建事件,当前在线用户数:"+(++onlineUserCount));
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        log.info("进入Session销毁事件,当前在线用户数:"+(--onlineUserCount));
    }
}

本文地址:https://blog.csdn.net/qq_42724864/article/details/107348826