@FeignClient("guli-cart")
public interface CartFenignService {
@GetMapping("/currentUserCartItems")
List<OrderItemVo> getCurrentUserCartItems();
}// 这样去掉接口时其实Feign在底层是一个全新的requst所有请求头就没有了
解决办法使用Feign远程掉用拦截器,在远程请求是先创建拦截器
@Bean("requestInterceptor")
public RequestInterceptor requestInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate template) {
/**
* 把以前的Cookie放到新请求中去 原理就是运用了同一线程数据共享 ThreadLocal
*/
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String cookie = request.getHeader("Cookie");
template.header("Cookie", cookie);
}
};
}
但是上面的办法只能解决同意线程问题,在多线程下还是会丢失请求头
多线程下解决办法:
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
把请求单独拿出来给每个线程单独
RequestContextHolder.setRequestAttributes(requestAttributes);
这样就可以了