参考代码
package org.dfmarketing.util;
import org.dfmarketing.constant.enums.ErrorMessageEnum;
import org.dfmarketing.exception.BusinessException;
import org.dfmarketing.vo.UserInfo;
/**
* @Description: 将用户信息存入ThreadLocal中
*/
public class UserThreadLocal {
private static final ThreadLocal<UserInfo> LOCAL = new ThreadLocal<>();
private UserThreadLocal() {
}
/**
* 将authUserInfo放到ThreadLocal中
*
* @param userInfo {@link UserInfo}
*/
public static void set(UserInfo userInfo) {
LOCAL.set(userInfo);
}
/**
* 从ThreadLocal中获取authUserInfo
*/
public static UserInfo get() {
return LOCAL.get();
}
/**
* 从当前线程中删除authUserInfo
*/
public static void remove() {
LOCAL.remove();
}
/**
* 从当前线程中获取用户id
* @return 用户id
*/
public static String getUserId() {
UserInfo userInfo = LOCAL.get();
if (userInfo == null || userInfo.getUserId() == null) {
throw new BusinessException(ErrorMessageEnum.TOKEN_ERROR);
}
return userInfo.getUserId();
}
}