在微服务实际开发当中,Feign负责远程调用,在调用过程中,我们的远程服务可能做了某些权限验证、或者接收我们自定义头的一些信息和参数,如果没有token或者某些参数,可能会无法调用甚至调用失败,当通过Feign调用其他的服务时,Feign是不会带上当前请求的Cookie信息和头信息的,而我们一般都会在Cookie或者请求头里带着一些重要的信息,如cookieid,token等
我们设置Feign的拦截器
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* ***************************************************
*
* @Auther:
* @Descipion:
* @CreateDate:
* ****************************************************
*/
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
@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);
// 跳过 content-length
if (name.equals("content-length")){
continue;
}
requestTemplate.header(name, values);
}
}
}
}
注意 上面代码中的注释 跳过 content-length 这个if 判断
参考文章:feign.RetryableException: too many bytes written executing POST
配置类
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* ***************************************************
*
* @Auther:
* @Descipion:
* @CreateDate:
* ****************************************************
*/
@Configuration
public class FeignSupportConfig {
/**
* feign请求拦截器
*
* @return
*/
@Bean
public RequestInterceptor requestInterceptor(){
return new FeignBasicAuthRequestInterceptor();
}
}
应该是将request请求头中的key,value取出,从新赋值给新的请求头,转给之后的服务
例如:A服务中接收到request请求,而A服务中使用Feign远程调用了B服务,那么A所接收到的requestHeader会组成新的请求头,在B中就可以使用这个新组成的请求头
转载地址:关于SpringCloud中使用Feign远程调用,丢失Header的问题