FeignClient设置请求头信息
1. FeignClient概述
这里所说的Feign都是指Open Feign,因为Netflix的Feign已经停更了,那什么是Feign,借用官网一句话就是,“Feign is a declarative web service client.” ,Feign就是一个声明试web service客户端。
具体详细说明详见官方文档:
Feign主要实现客户端负载均衡与远程调用的作用,OpenFeign实在Feign基础上再次封装,Feign集成了Ribbon,在OpenFeign之前采用Ribbon+RestTemplate方式实现负载均衡与远程调用,而OpenFeign则集成了这两者,所以OpenFeign就是Ribbon+RestTemplate。
实现客户端调用方式有很多hutool的httpclient,直接使用httpclient,也包括FeignClient,在客户端端调用过程中不同业务场景及不同系统调用方式不同,有时候需要设置不同的头信息。
2. FeignClient设置请求头信息
2.1 实现方式一
直接写在方法请求注解PostMapping上:
@PostMapping(headers = {"AccessKey=xxxxxx"})
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.net.URI; import java.util.LinkedHashMap; /** * 平台接口 * * @author zrj * @since 2021/8/2 **/ @Service("SearchService") @FeignClient(url = "https://hello.com/search-api/", name = "SearchService") public interface SearchPlatformService { /** * 新增数据 */ @PostMapping(headers = { "AccessKey=xxxxxxxx"}) LinkedHashMap insertDoc(URI uri, @RequestBody LinkedHashMap linkedHashMap); /** * 搜索数据 */ @PostMapping(headers = { "AccessKey=xxxxxxxx"}) LinkedHashMap selectDoc(URI uri, @RequestBody LinkedHashMap linkedHashMap); }
2.2 实现方式二
通过Feign配置类feign configuration 实现全局的请求头和 token设置,相当于每次feign请求都会自动带上这些头信息。
/** * 客户端设置头信息 * * @author zrj * @since 2021/11/11 **/ @Slf4j @Configuration public class ClientConfiguration { @Value("${hello.search.headers}") private String headers; @Bean public RequestInterceptor headerInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { //List<String> authorizationList = Lists.newArrayList("Bearer "+tokenId); //List<String> contentTypeList = Lists.newArrayList("application/x-www-form-urlencoded;charset=utf-8"); //Map<String, Collection<String>> headers =ImmutableMap.of("Authorization", authorizationList,"Content-Type", contentTypeList); //template.headers(headers); template.header("AccessKey", headers); } }; } } /** * 搜索平台接口 * * @author zrj * @since 2021/8/2 **/ @Service("SearchService") @FeignClient(url = "https://hello.com/search-api/", name = "SearchService") public interface SearchPlatformService { /** * 新增数据 */ @PostMapping LinkedHashMap insertDemo(URI uri, @RequestBody LinkedHashMap linkedHashMap); /** * 搜索数据 */ @PostMapping LinkedHashMap selectDemo(URI uri, @RequestBody LinkedHashMap linkedHashMap); }
参考文档