创建 Feign 拦截器
public class FeignRequestInterceptorConfig implements RequestInterceptor {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (null != attributes) {
HttpServletRequest request = Objects.requireNonNull(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);
}
logger.debug("feign interceptor header:{}", template);
}
}
}
}
若要在子线程中进行 Feign 调用时
@Override
public void syncOrder(MyHttpServletRequest myHttpServletRequest, List<Long> ids) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
CompletableFuture.runAsync(() -> {
RequestContextHolder.setRequestAttributes(attributes);
//此后进行feign调用
...
}
}