在Spring Cloud中,使用Feign进行服务之间的调用时,默认情况下是不会传递header的。如果需要传递header,可以通过以下几种方式实现:
@FeignClient(name = "other-service")
public interface OtherServiceClient {
@GetMapping("/api/some-resource")
ResponseEntity<String> getSomeResource(@RequestHeader("Authorization") String token);
}
@Configuration
public class FeignClientConfig {
public HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
@Bean
public RequestInterceptor requestInterceptor() {
return template -> {
template.header("platform", getRequest().getHeader("platform"));
};
}
}
feign:
client:
config:
default:
loggerLevel: full
requestInterceptors:
- com.example.MyRequestInterceptor
public class MyRequestInterceptor implements RequestInterceptor {
public HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
@Override
public void apply(RequestTemplate template) {
template.header("platform", getRequest().getHeader("platform"));
}
}
以上是三种常用的方式,根据具体的需求选择适合的方式即可。