做电影网站考什么,东莞工厂,模具外发加工订单网,seo站长工具推广平台BaseContext ThreadLocal 并不是一个Thread#xff0c;而是Thread的局部变量。 ThreadLocal为每个线程提供单独一份存储空间#xff0c;具有线程隔离的效果#xff0c;只有在线程内才能获取到对应的值#xff0c;线程外则不能访问。 public void set(T value) 设置当前线程…BaseContext ThreadLocal 并不是一个Thread而是Thread的局部变量。 ThreadLocal为每个线程提供单独一份存储空间具有线程隔离的效果只有在线程内才能获取到对应的值线程外则不能访问。 public void set(T value) 设置当前线程的线程局部变量的值 public T get() 返回当前线程所对应的线程局部变量的值 public void remove() 移除当前线程的线程局部变量 public class BaseContext {public static ThreadLocalLong 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();}}
在拦截器中将当前用户的信息放入threadlocal
/*** jwt令牌校验的拦截器*/
Component
Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {Autowiredprivate JwtProperties jwtProperties;/*** 校验jwt** param request* param response* param handler* return* throws Exception*/public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//.............................//2、校验令牌try {//.................Claims claims JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);Long empId Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());log.info(当前员工id, empId);/将用户id存储到ThreadLocalBaseContext.setCurrentId(empId);//3、通过放行return true;} catch (Exception ex) {//......................}}
}
然后在想要使用的地方调用getCurrentId方法就可以