SpringBoot之ThreadLocal保存请求用户信息
一、ThreadLocal概述
线程局部变量,创建一个线程变量后,针对这个变量可以让每个线程拥有自己的变量副本,每个线程是访问的自己的副本,与其他线程的相互独立。
二、具体代码demo实现
(1)创建user实例对象
@Data public class UserDTO { private Long userId; private String UserName; }
(2)创建UserThreadLocal对象
public class UserThreadLocal { private UserThreadLocal(){}; private static final ThreadLocal<UserDTO> USER_DTO_THREAD_LOCAL = new ThreadLocal<>(); /** * 清除信息 */ public static void clear(){ USER_DTO_THREAD_LOCAL.remove(); } /** * 保存用户信息 * @param userDTO */ public static void set(UserDTO userDTO){ USER_DTO_THREAD_LOCAL.set(userDTO); } public static UserDTO getCurrentUser(){ return USER_DTO_THREAD_LOCAL.get(); } }
(3)创建用户拦截器
@Component public class UserInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //此处实际应该根据header的token解析出用户本处为了简单,直接虚构一个用户 UserDTO userDTo = new UserDTO(); userDTo.setUserId(10001L); userDTo.setUserName("张三"); UserThreadLocal.set(userDTo); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { UserThreadLocal.clear(); } }
(4) 注册用户拦截器
@Configuration public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new UserInterceptor()); } }
(5)编写测试接口
@RequestMapping("test") @RestController public class TestController { @GetMapping("get") public UserDTO getUser(){ UserDTO currentUser = UserThreadLocal.getCurrentUser(); System.out.println(currentUser); return currentUser; } }
(6)效果展示
古今成大事者,不唯有超世之才,必有坚韧不拔之志!