Springboot+jwt实现在线用户功能(示例代码)
作者:修罗-zero
这篇文章主要介绍了Springboot+jwt实现在线用户功能,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
1.定义OnlineCounter用于记录在线人员
package com.example.demo.config;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/*
* 在线用户
* */
@Component
public class OnlineCounter {
private static Map countMap = new ConcurrentHashMap<String,Object>();
public void insertToken(String token){
//获取当前时间(毫秒)
//解析token
String userId = TokenUtil.getUserId(token);
countMap.put(userId,token);
}
/*
* 获取当前在线总数
* */
public Integer getOnlineCount(){
int onlineCount = 0;
//获取countMap的迭代器
Iterator iterator = countMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String,Object> entry = (Map.Entry<String,Object>) iterator.next();
String token = (String) entry.getValue();
boolean flag = TokenUtil.hasExpiresAt(token);//返回true就是过期了
if(flag){
//移除
countMap.remove(entry.getKey());
}else{
onlineCount++;
}
}
return onlineCount;
}
/*
* 获取当前在线用户列表
* */
public List<String> getOnlineUserList(){
List<String> userIdList = new ArrayList<>();
//获取countMap的迭代器
Iterator iterator = countMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String,Object> entry = (Map.Entry<String,Object>) iterator.next();
String token = (String) entry.getValue();
boolean flag = TokenUtil.hasExpiresAt(token);//返回true就是过期了
if(flag){
//移除
countMap.remove(entry.getKey());
}else{
userIdList.add(entry.getKey());
}
}
return userIdList;
}
}2.定义一个拦截器,主要在验证通过拦截器的时候调用上面的方法插入一个新用户
@component
public class JWTInterceptor implements HandlerInterception{
@Autowired
private OnlineCounter onlineCounter;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
return true;
} else {
//jwt业务逻辑代码。。。。。。
//记录在线人员
onlineCounter.insertUser(userId);
return true;
}
}
}

工具类需要新增方法用于判断当前token是否过期
/*
* 根据token判断是否过期
* */
public static boolean hasExpiresAt(String token){
//创建token验证器
try{
JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
DecodedJWT decodedJWT=jwtVerifier.verify(token);
Date timeoutDate = decodedJWT.getExpiresAt();//获取过期时间
long diffTime = timeoutDate.getTime() - new Date().getTime();//获取过期时间与当前时间的时间差(毫秒)
System.out.println("过期时间与当前时间的时间差(毫秒):"+diffTime);
if(diffTime < 0){
//已过期
return true;
}else{
//未过期
return false;
}
}catch (Exception e){
return true;
}
}3.定义个控制器 获取在线人员数量OnlineController
@ApiController(value = "/sys/online")
public class OnlineController {
@Autowired
private OnlineCounter onlineCounter;
/**
* 获取当前用户在线人数
*
* @return
*/
@GetMapping(value = "/getOnlineCount")
public int getRealOnlineCount() {
Integer onlines = onlineCounter.getOnlineCount();
return onlines;
}
}
调用接口,结果如下:

到此这篇关于Springboot+jwt实现在线用户功能的文章就介绍到这了,更多相关Springboot jwt在线用户内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
