解决Spring cloud项目中多线程中使用feign访问其他服务失败问题

微服务中尝试使用多线程访问其他服务,通过服务接口调用失败,

解决Spring cloud项目中多线程中使用feign访问其他服务失败问题

通过Debug模式,跟随子线程调用链,发现处理服务发送时的请求头设置中,

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
        .getRequestAttributes();

HttpServletRequest request = attributes.getRequest();

获取的request为null,

解决Spring cloud项目中多线程中使用feign访问其他服务失败问题

通过度娘几番查找,找到一篇文章解决request为null的问题,

https://blog.****.net/schcilin/article/details/92403362

通过文章发现,在Spring cloud微服务中,feign开启了熔断器(hystrix):feign.hystrix.enabled=ture,并且使用默认的信号隔离级别,、HttpServletRequest对象在父线程与子线程是相互独立的,不共享的。所以子线程中使用父线程的HttpServletRequest数据为null。

在我的测试代码中使用feign API接口前调用

RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);

来设置将父线程的HttpServletRequest对象设置共享,

解决Spring cloud项目中多线程中使用feign访问其他服务失败问题