ThreadLocal线程局部变量存储用户ID

77 阅读1分钟

1、定义上下文类

 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();
     }
 }

2、在拦截器中解析JWT令牌,拿到用户ID后,进行存储

  @Component
  public class JwtTokenInterceptor implements HandlerInterceptor {
  
      @Autowired
      private JwtProperties jwtProperties;
  
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  
          // 从请求头获取令牌
          String token = request.getHeader(jwtProperties.getTokenName());
          if (token == null) {
              response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
              return false;
          }
  
          // 校验令牌
          try {
              Claims claims = JwtUtil.parseToken(token, jwtProperties);
              Long userId = Long.valueOf(claims.get("userId").toString());
              
              // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
              // 存储用户ID至线程局部变量
              BaseContext.setCurrentId(empId);
              
              return true;
          } catch (Exception ex) {
              // 校验失败,响应401状态码
              response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
              return false;
          }
      }
  }