VrApiContext.java
2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.glsx.usedcar.context;
import com.glsx.usedcar.module.inspect.entity.Inspector;
import lombok.extern.slf4j.Slf4j;
/**
* 检测师上下文对象
*/
@Slf4j
public class VrApiContext {
/**
* 存储当前线程的用户信息,KEY 命名与存储内容匹配(原 USER_NAME_TL 命名不规范,已修正)
*/
private static final ThreadLocal<Inspector> VR_TL = new ThreadLocal<>();
/**
* 保存用户信息到当前线程上下文
*
* @param user 用户信息DTO(允许传 null,代表无登录用户)
*/
public static void saveVr(Inspector user) {
if (user != null) {
VR_TL.set(user);
}
}
/**
* 获取当前线程的用户信息
*
* @return 用户信息DTO(无登录用户时返回 null)
*/
public static Inspector getInspector() {
return VR_TL.get();
}
/**
* 清除当前线程的用户信息(必须调用,防止 ThreadLocal 内存泄漏)
*/
public static void removeInspector() {
try {
VR_TL.remove();
log.debug("用户上下文已清除当前线程的用户信息");
} catch (Exception e) {
log.error("清除用户上下文失败", e);
}
}
/**
* 获取当前登录用户ID
*
* @return 检测师ID
*/
public static Long getInspectorId() {
Inspector inspector = getInspector();
return inspector == null ? null : inspector.getId();
}
/**
* 获取当前登录用户手机号(无登录用户返回 null)
*
* @return 用户手机号
*/
public static String getPhone() {
Inspector inspector = getInspector();
return inspector == null ? null : inspector.getPhone();
}
/**
* 判断当前线程是否有登录用户
*
* @return true-已登录,false-未登录
*/
public static boolean hasLogin() {
return getInspector() != null;
}
public static Object getInspectorName() {
Inspector inspector = getInspector();
if (inspector == null) {
return "未登录用户";
}
return inspector.getName();
}
}