每个接口都要获取token来拿用户信息? 拦截器+线程池 优化 token
1,创建线程池:
public class UserHolder { private static ThreadLocal<User> tl =new ThreadLocal<User>(); // 存数据 public static void saveUser(User user){ tl.set(user); } //取数据 public static User getUser(){ return tl.get(); } //删除数据 public static void removeUser(){ tl.remove(); } }
2,创建拦截器:
@Component public class TokenInterceptor implements HandlerInterceptor { @Autowired private UserService userService; @Override//在controller前拦截 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 获取token getHeader获取单个请求头Authorization对应的value值 String token = request.getHeader("Authorization");//请求参数Authorization 令牌=token if (token == null) { response.setStatus(400); return false; } User user = userService.fromRedisUser(token); if(user==null){ response.setStatus(400); //权限不足 return false;//中断请求 } // 将用户放在threadLocal中 UserHolder.saveUser(user); // 放行 return true; } @Override//响应结束 threadLocal移除对象 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { UserHolder.removeUser(); //移除对象 } }
这样,需要根据token来获取用户信息的地方就可以直接:
User user = UserHolder.getUser();
再也不用每次都往接口里传token了
未经允许 禁止转载