在微服务间使用Feign进行远程调用时需要在 header 中添加信息,那么 SpringBoot和SpringCloud OpenFeign的@FeignClient如何设置 header 呢?有5种方式可以设置请求头信息:
• 在@RequestMapping注解里添加headers属性
• 在方法参数前面添加@RequestHeader注解
• 实现RequestInterceptor接口
由于Feign是完全支持Spring MVC注解的, 所以推荐使用前两种Feign设置header的方式, 即: Spring MVC中使用注解设置header.
在application.yml中配置
my.name=wtl
@PostMapping(value = "/service/rest/v1/script/{scriptName}/run",headers = {"Authorization=Basic YWRtaW46QFdUTDE5OTIwMTE4MDI3MQ==","Content-Type=text/plain","AppSecret=${my.name}"})
String runScript(@PathVariable("scriptName") String scriptName);
设置单个header属性
@PostMapping(value = "/service/rest/v1/script/{scriptName}/run",headers = {"Content-Type=text/plain","AppSecret=${my.name}"})
String runScript(@PathVariable("scriptName") String scriptName,@RequestHeader("Authorization") String authorization);
public String runScript(String scriptName) {
return nexusOpenFeign.runScript(scriptName,"Basic YWRtaW46QFdUTDE5OTIwMTE4MDI3MQ==");
}
设置多个header属性
@PostMapping(value = "/service/rest/v1/script/{scriptName}/run")
String runScript(@PathVariable("scriptName") String scriptName,@RequestHeader MultiValueMap headers);
public String runScript(String scriptName) {
MultiValueMap headers = new HttpHeaders();
headers.put("Authorization", Collections.singletonList("Basic YWRtaW46QFdUTDE5OTIwMTE4MDI3MQ=="));
headers.add("Content-Type","text/plain");
return nexusOpenFeign.runScript(scriptName,headers);
}
如果FeignRequestInterceptor注入到spring容器的话就会全局生效, 就是说即使在没有指定configuration属性的FeignClient该配置也会生效。
配置@Component或@Service 或 @Configuration 就可以将该配置注入spring容器中, 即可实现全局配置, 从而该项目中的所有FeignClient的feign接口都可以使用该配置.
如果只想给指定FeignClient的feign接口使用该配置, 请勿将该类配置注入spring中。
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
template.header(HttpHeaders.AUTHORIZATION, "tokenVal");
}
}
@FeignClient(url = "${user.api.url}", name = "user", configuration = FeignRequestInterceptor.class)
public interface UserFeignClient {
@GetMapping(value = "/simple/{id}")
public User findById(@RequestParam("id") String id);
}