ThreadLocal为每个线程提供单独一份存储空间,具有线程隔离的效果,只有线程内才能获取
封装一下上下文方法,建一个单例
public class BaseContext {
public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
public static void setCurrentId(Long id) {
threadLocal.set(id);
}
public static Long getCurrentId() {
return threadLocal.get();
}
public static void removeCurrentId() {
threadLocal.remove();
}
}
存储令牌解析信息
// 设置当前线程局部变量的值
// 解析出当前jwt令牌中的值
Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
// 存入线程上下文
BaseContext.setCurrentId(empId);
// 在Service层中获取
employee.setCreateUser(BaseContext.getCurrentId());
employee.setUpdateUser(BaseContext.getCurrentId());