美文网首页
SpringBoot使用Feign调用三方接口

SpringBoot使用Feign调用三方接口

作者: 小胖学编程 | 来源:发表于2023-11-23 18:06 被阅读0次

一直以来,都以为Feign接口只能在SpringCloud体系中,调用注册中心中的微服务,但是SpringBoot+feign亦可以调用三方的http接口。

引入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>

编写代码:

  1. 启动类上加上@EnableFeignClients(basePackages="路径")
  2. 直接编写接口类:
 //类似于编写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);
}
  1. 因为调用外部接口需要在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);
    }
}

文档参考

SpringBoot项目中使用feign调用远程http接口(超详细文档)

feign调用时使用RequestInterceptor设置request对象

相关文章

网友评论

      本文标题:SpringBoot使用Feign调用三方接口

      本文链接:https://www.haomeiwen.com/subject/tfsgwdtx.html