一直以来,都以为Feign接口只能在SpringCloud体系中,调用注册中心中的微服务,但是SpringBoot+feign亦可以调用三方的http接口。
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
编写代码:
- 启动类上加上
@EnableFeignClients(basePackages="路径")
- 直接编写接口类:
//类似于编写Controller接口,openapi.url就是三方的url地址
@FeignClient(name = "xxx", url = "${openapi.url}", decode404 = true, configuration = xxxApiConfiguration.class)
public interface OpenApiClient {
@GetMapping("/rest/get")
ResponseDto<String> getXxx(@RequestParam String id);
}
- 因为调用外部接口需要在header里面填写信息,以便于鉴权。所以需要在xxxApiConfiguration中定义RequestInterceptor来完成鉴权。
@Configuration
public class XxxApiConfiguration {
@Bean
public XxxAccessTokenInterceptor kwaiOpenAccessTokenInterceptor() {
return new XxxAccessTokenInterceptor();
}
}
请求拦截器
@Service
public class XxxAccessTokenInterceptor implements RequestInterceptor {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void apply(RequestTemplate requestTemplate) {
//设置字段
requestTemplate.header("auth", "token=" + token);
}
}