update 优化 在线用户功能 使用 spring-cache 管理

This commit is contained in:
疯狂的狮子Li
2022-08-14 01:50:00 +08:00
parent f9a9431958
commit 8837119aad
2 changed files with 16 additions and 11 deletions

View File

@ -5,20 +5,18 @@ import cn.dev33.satoken.listener.SaTokenListener;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.CacheNames;
import com.ruoyi.common.core.domain.dto.UserOnlineDTO;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.redis.CacheUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
/**
* 用户行为 侦听器的实现
*
@ -50,7 +48,12 @@ public class UserActionListener implements SaTokenListener {
dto.setTokenId(tokenValue);
dto.setUserName(user.getUsername());
dto.setDeptName(user.getDeptName());
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto, Duration.ofSeconds(tokenConfig.getTimeout()));
String cacheNames = CacheNames.ONLINE_TOKEN;
if (tokenConfig.getTimeout() > 0) {
// 增加 ttl 过期时间 单位秒
cacheNames = CacheNames.ONLINE_TOKEN + "#" + tokenConfig.getTimeout() + "s";
}
CacheUtils.put(cacheNames, tokenValue, dto);
log.info("user doLogin, userId:{}, token:{}", loginId, tokenValue);
} else if (userType == UserType.APP_USER) {
// app端 自行根据业务编写
@ -62,7 +65,7 @@ public class UserActionListener implements SaTokenListener {
*/
@Override
public void doLogout(String loginType, Object loginId, String tokenValue) {
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
CacheUtils.evict(CacheNames.ONLINE_TOKEN, tokenValue);
log.info("user doLogout, userId:{}, token:{}", loginId, tokenValue);
}
@ -71,7 +74,7 @@ public class UserActionListener implements SaTokenListener {
*/
@Override
public void doKickout(String loginType, Object loginId, String tokenValue) {
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
CacheUtils.evict(CacheNames.ONLINE_TOKEN, tokenValue);
log.info("user doLogoutByLoginId, userId:{}, token:{}", loginId, tokenValue);
}
@ -80,7 +83,7 @@ public class UserActionListener implements SaTokenListener {
*/
@Override
public void doReplaced(String loginType, Object loginId, String tokenValue) {
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
CacheUtils.evict(CacheNames.ONLINE_TOKEN, tokenValue);
log.info("user doReplaced, userId:{}, token:{}", loginId, tokenValue);
}