Solution when provider cannot obtain parameter value from request when using feign
question:
During development, project A needs to call the feign interface of project B on the backend. The original parameter reception of project B is in httpServletRequest, as shown below:
We know that the feign interface does not support HttpServletRequest as a parameter, so the feign interface is as follows
analyze:
Since the feign interface is called on the sub-link in the consumer, request does not support inheritance. When calling the feign interface, the original request will not be followed by the new request, so the request in the provider is empty and the parameter value cannot be obtained.
Solution
The value in request is manually set to the http call of feign request.
@Configuration
public class OpenFeignConfig implements RequestInterceptor {
private static final org.slf4j.Logger _logger = LoggerFactory.getLogger(OpenFeignConfig.class);
/**
* NONE(默认):不记录任何日志,性能最佳,适用于生产环境;
* BASIC:仅记录请求方法、URL、响应状态代码以及执行时间,适用于生产环境追踪问题;
* HEADERS:在BASIC级别的基础上,记录请求和响应的header;
* FULL:记录请求和响应的header、body和元数据,适用于开发测试定位问题。
*
* @return {@link Logger.Level }
* @Author wangxiaole
* @Date 2023/09/07
**/
@Bean
Logger.Level feginLoggerLevel() {
return Logger.Level.FULL;
}
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
// 传递所有请求头,防止部分丢失
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
requestTemplate.header(name, values);
}
}
}
}