项目场景:
收到了告警,调用fein接口应该抛异常的,但是流程正常执行了。
这个时候细看了下代码
{
executorService.submit(()->{
feign1;
feign2;
}
feign1本该抛异常,反而是继续执行feign2
原因分析:
经过debug,发现在底层包feignconfiguration中的headerInteceptor方法中,
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return;
}
请求头解析中,attributes返回空,所以就没有执行解析。
接着分析为啥attributes为空,getRequestAttributes()这个方法使用的是本地线程
原来是因为使用了异步多线程下,使用的是ThreadLocal,可以拿到同一个线程携带的数据,但是不同线程的数据,拿不到的。而
解决方案:
我们可以在方法内的局部变量中先保存原来线程的信息,在异步编排的新线程中拿着局部变量的值重新设置到新线程中即可。
{
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
executorService.submit(()->{
RequestContextHolder.setRequestAttributes(requestAttributes);
feign1;
feign2;
}