微服务调用的时候请求不会传递参数.比如调用方服务请求头中有cookie存放sessionId,而被调用方服务没有请求头,从而没有cookie信息,也就不能根据cookie中存放的sessionId获取session信息,影响后续操作.
解决办法
通过实现RequestInterceptor接口,完成对所有的Feign请求,传递请求头和请求参数。本质是通过ThreadLocal线程共享变量实现.
import feign.RequestInterceptor; import feign.RequestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @Configuration public class FeignConfig { /** * 解决feign远程调用丢失请求头的问题 * @return */ @Bean public RequestInterceptor requestInterceptor(){ return new RequestInterceptor(){ @Override public void apply(RequestTemplate requestTemplate) { //老请求 获取老请求的cookie信息 ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (requestAttributes != null){ String cookie = requestAttributes.getRequest().getHeader("Cookie"); //同步到新请求中 requestTemplate.header("Cookie",cookie); } } }; } }