由于一些业务处理,在远程调用Feign时,需要异步调用,但是当前请求上下文是保存在ThreadLocal中,这样会导致上下文丢失。
公司业务需要在批量导入数据,文件上传成功,异步解析数据入库。
feign 拦截器配置如下
在远程调用中header进行向下传递
@Component
@Slf4j
public class FeignConfiguration implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
template.header(name, values);
}
}
}
}
}
代码处理如下
额外问题
主线程为文件上传,在异步线程中调用一个get请求的feign时,服务会包,文件上传错误的问题,这是因为要在调用feign的GetMapping中写,请求类型。如下