美文网首页
springboot在线人数统计

springboot在线人数统计

作者: 85年的大喇叭 | 来源:发表于2023-11-26 20:46 被阅读0次

转载自:www.javaman.cn

笔者做了一个网站,需要统计在线人数。

在线有两种:

一、如果是后台系统如果登录算在线,退出的时候或者cookie、token失效的时候就算下线

二、如果是网站前台,访问的时候就算在线

今天我们来讲一下第2种情况,网站前台如何统计同时在线人数

1、首先创建一个在线人数管理类

该类主要是管理登录的session信息

<pre mdtype="fences" cid="n129" lang="java" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" spellcheck="false" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> package com.ds.blog.admin.manager;

import java.util.HashSet;
import java.util.Set;

public class OnlineUserManager {

//创建数据类型set来存储session
private static final Set<String> onlineUsers = new HashSet<>();

//添加访问
public static void addUser(String sessionId){
onlineUsers.add(sessionId);
}

//删除访问
public static void removeUser(String sessionId){
onlineUsers.remove(sessionId);
}

//获取在线人数
public static Set<String> getOnlineUsers(){
return onlineUsers;
}

}
</pre>

2、创建拦截器用于增加访问次数

当用户访问首页或者详情页的时候,拦截器获取sessionid,存入onlineUsers中

<pre mdtype="fences" cid="n139" lang="java" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" spellcheck="false" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> package com.ds.blog.admin.interceptor;

import com.ds.blog.admin.manager.OnlineUserManager;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OnlineInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getRequestURI().contains("/front")){
System.out.println("pre begin");
// 保存访问人数
OnlineUserManager.addUser(request.getSession().getId());
System.out.println("pre end");
}
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (request.getRequestURI().contains("/front")){
System.out.println("postHandle begin");
// 在处理完请求后调用,可以对ModelAndView进行操作
if (modelAndView != null) {
modelAndView.addObject("onlineUsers", OnlineUserManager.getOnlineUsers().size());
}
System.out.println("postHandle end");
}
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}

}</pre>

3、注册第2步的拦截器

<pre mdtype="fences" cid="n143" lang="java" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" spellcheck="false" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> package com.ds.core.config;

import com.ds.blog.admin.interceptor.OnlineInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new OnlineInterceptor());
}
}</pre>

前三步做完以后,就可以实现在线人数了。

4、网页实现

<pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="html" cid="n153" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> <p th:text="'当前在线人数: ' + ${onlineUsers}"></p></pre>

效果如下:

[图片上传失败...(image-8d0373-1700323003642)]

<mark style="box-sizing: border-box; background: rgb(255, 255, 0); color: rgb(0, 0, 0);">但是有一个问题,如果用户关闭访问的页面,同时在线人数不会下降,原因是因为前端认为关闭页面才算作退出在线人数。所以当页面关闭的时候,触发onlineUserManger的removeUser方法,就需要第5和第6步的实现</mark>

5、前端controller添加关闭页面时调用的controller

页面关闭时,会调用removeSession方法

<pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="java" cid="n169" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> /**

  • @return
    */
    @BookLog(title = "关闭页面时减少在线人数",businessType = BusinessType.DELETE)
    @ApiOperation(value = "获取文章内容")
    @PostMapping(value = "blog/updateOnlineUsers")
    @ResponseBody
    public Result removeSession(HttpServletRequest request){
    try {
    OnlineUserManager.removeUser(request.getSession().getId());
    } catch (Exception exception) {
    exception.printStackTrace();
    }
    return Result.success("减少成功");
    }</pre>

6、页面关闭时,js触发controller

<pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="javascript" cid="n174" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"> window.onbeforeunload = function() {
$.ajax({
url: 'blog/updateOnlineUsers',
method: 'POST',
success: function(response) {
console.log('关闭成功')
}
});
}</pre>

总体功能完成,我们来看下效果

ie浏览器登录,在线人数为1

[图片上传失败...(image-7dd431-1700323003641)]

谷歌浏览器登录,在线人数为2

[图片上传失败...(image-752768-1700323003641)]

关闭ie浏览器,刷新谷歌浏览器当前在线人数降为1

[图片上传失败...(image-91f479-1700323003641)]

相关文章

网友评论

      本文标题:springboot在线人数统计

      本文链接:https://www.haomeiwen.com/subject/ndmuwdtx.html