feat(login): 优化用户登出功能并增强日志记录
- 添加 CacheManager 导入以支持缓存管理 - 从 Redis 中删除用户信息后增加从缓存中移除 token 映射逻辑 - 添加用户名和 token 的双向缓存清理机制 - 集成 Sa-Token 登出流程并完善异常处理 - 添加登出成功和异常的日志记录功能 - 优化注释描述提高代码可读性
This commit is contained in:
parent
7ae6e19ae1
commit
8e25f10b27
|
|
@ -1,6 +1,7 @@
|
|||
package com.kexue.skills.controller;
|
||||
|
||||
import com.kexue.skills.annotation.PreventDuplicateSubmission;
|
||||
import com.kexue.skills.common.CacheManager;
|
||||
import com.kexue.skills.common.CommonResult;
|
||||
import com.kexue.skills.entity.request.LoginDto;
|
||||
import com.kexue.skills.entity.request.LoginUserDto;
|
||||
|
|
@ -13,6 +14,8 @@ import org.springframework.web.bind.annotation.*;
|
|||
import javax.annotation.Resource;
|
||||
import org.redisson.api.RedissonClient;
|
||||
|
||||
import static cn.dev33.satoken.SaManager.log;
|
||||
|
||||
/**
|
||||
* (SysUser)表控制层
|
||||
*
|
||||
|
|
@ -58,20 +61,27 @@ public class LoginController {
|
|||
@Operation(summary = "用户登出", description = "用户登出")
|
||||
public CommonResult<String> logout() {
|
||||
try {
|
||||
// 获取当前用户的token
|
||||
// 获取当前用户的 token
|
||||
String token = cn.dev33.satoken.stp.StpUtil.getTokenValue();
|
||||
|
||||
// 使用Sa-Token登出
|
||||
cn.dev33.satoken.stp.StpUtil.logout();
|
||||
|
||||
// 从Redis中删除用户信息
|
||||
|
||||
// 从 Redis 中删除用户信息
|
||||
if (token != null && !token.isEmpty()) {
|
||||
redissonClient.getBucket("loginUser:" + token).delete();
|
||||
// 从缓存中移除 token 映射
|
||||
String username = CacheManager.getUsernameFromToken(token);
|
||||
if (username != null) {
|
||||
CacheManager.removeTokenFromCache(username);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 使用 Sa-Token 登出(这会清除 Sa-Token 内部的会话信息)
|
||||
cn.dev33.satoken.stp.StpUtil.logout();
|
||||
|
||||
log.info("用户登出成功,token 已清理");
|
||||
return CommonResult.success("登出成功");
|
||||
} catch (Exception e) {
|
||||
// 如果获取token失败,仍然执行登出操作
|
||||
log.error("登出异常:{}", e.getMessage());
|
||||
// 如果获取 token 失败,仍然执行登出操作
|
||||
cn.dev33.satoken.stp.StpUtil.logout();
|
||||
return CommonResult.success("登出成功");
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue