微服务等情况下,通过feign调用接口,很多情况下需要在fegin所在的服务中心获取header等等的信息,默认情况下是不带有的。
所以,最好是自行处理,转发所有,以下以header为例
@Slf4j标签:Map,Feign,请求,ServletRequestAttributes,enumeration,header,attributes,null From: https://blog.51cto.com/u_15595167/6112875
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if(null == attributes){
log.info("attributes在feginConfig中没有获取到");
attributes = new ServletRequestAttributes((HttpServletRequest) new MockHttpServletRequest());
RequestContextHolder.setRequestAttributes(attributes);
}
HttpServletRequest request = attributes.getRequest();
log.info("RequestTemplate.headers:" + JSON.toJSONString(requestTemplate.headers()));
if (null != httpServletRequest) {
Map<String, String> headers = getHeaders(httpServletRequest);
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestTemplate.header(entry.getKey(), entry.getValue());
}
}
}
private HttpServletRequest getHttpServletRequest() {
try {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private Map<String, String> getHeaders(HttpServletRequest request) {
Map<String, String> map = new LinkedHashMap<>();
Enumeration<String> enumeration = request.getHeaderNames();
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
}
return map;
}
}