CurrentUser.java
2.41 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
85
86
87
88
89
90
91
92
package com.dituhui.mp.pojo;
import brave.Tags;
import brave.Tracer;
import brave.baggage.BaggageField;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/***
* 当前用户类
* @author dk
*/
@Component
public class CurrentUser {
@Autowired
Tracer tracer;
/**
* 当前线程用户信息
*/
public static ThreadLocal<PlatformUser> threadPlatformUser = new ThreadLocal<PlatformUser>();
/**
* 创建当前线程对应的用户
*
* @return
*/
private PlatformUser createPlatformUser() {
// 如果没有用户信息则创建
PlatformUser user = new PlatformUser();
String tagTrace = this.tracer.currentSpan().context().traceIdString();
if (StringUtils.isNotEmpty(tagTrace)) {
user.setIdLog(tagTrace);
}
String tagToken = getBaggageFieldValue("token");
if (StringUtils.isNotEmpty(tagToken)) {
user.setToken(tagToken);
}
String tagClientIp = getBaggageFieldValue("clientIp");
if (StringUtils.isNotEmpty(tagClientIp)) {
user.setClientIP(tagClientIp);
}
user.setUserId(getBaggageFieldValue("userId"));
user.setTeamId(getBaggageFieldValue("teamId"));
user.setT(getBaggageFieldValue("t"));
return user;
}
/**
* 获取用户请求标签
*
* @param name 参数名称
* @return
*/
private String getBaggageFieldValue(String name) {
BaggageField baggageField = BaggageField.create(name);
return Tags.BAGGAGE_FIELD.value(baggageField, this.tracer.currentSpan().context());
}
/**
* 获取 用户信息
*
* @return 用户信息
*/
public PlatformUser getPlatformUser() {
PlatformUser platformUser = threadPlatformUser.get();
if (null == platformUser || StringUtils.isEmpty(platformUser.getUserId())) {
platformUser = createPlatformUser();
threadPlatformUser.set(platformUser);
}
return platformUser;
}
/**
* 设置 用户信息
*
* @param user 用户信息
*/
public void setPlatformUser(PlatformUser user) {
threadPlatformUser.set(user);
}
/**
* 移除当前线程用户
*/
public void removePlatformUser() {
threadPlatformUser.remove();
}
}