SpringBoot 微服务中怎么获取用户信息 token
当我们写了一个A接口,这个接口需要调用B接口,但是B接口需要包含请求头内容,比如需要用户信息、用户id等内容,由于不在同一个线程中,使用ThreadLocal
去获取数据是无法获取的,这个时候需要手动将信息放置请求头中。
前置知识
获取请求头方式
return BaseContext.getUserId();
是我随便写的不要在意!!!
第一种 ServletRequestAttributes
通过ServletRequestAttributes
获取请求。
@GetMapping("/token")
public Long getToken() {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String token = request.getHeader("token");
return BaseContext.getUserId();
}
第二种 HttpServletRequest
@GetMapping("/token")
public Long getToken(HttpServletRequest request) {
String token = request.getHeader("token");
return BaseContext.getUserId();
}
第二种 通过注解
@GetMapping(