SpringBoot使用OpenFeign访问第三方接口配置方法(最新版本)

一、为SpringBoot项目添加依赖

由于SpringBoot版本和OpenFeign版本有对应关系,这里要根据自己使用的SpringBoot版本来确定如何引入OpenFeign。


以下内容取自官网

Release Train Spring Boot Generation
2023.0.x aka Leyton 3.2.x
2022.0.x aka Kilburn 3.0.x, 3.1.x (Starting with 2022.0.3)
2021.0.x aka Jubilee 2.6.x, 2.7.x (Starting with 2021.0.3)
2020.0.x aka Ilford 2.4.x, 2.5.x (Starting with 2020.0.3)
Hoxton 2.2.x, 2.3.x (Starting with SR5)
Greenwich 2.1.x
Finchley 2.0.x
Edgware 1.5.x
Dalston 1.5.x

举例:对于SpringBoot为3.2.3的情况,需要引入Feign版本为2023.0.0


maven配置方法

<properties>
    <spring-cloud.version>2023.0.0</spring-cloud.version>
</properties>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

gradle配置方法

ext {
  set('springCloudVersion', "2023.0.0")
}

dependencyManagement {
  imports {
    mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
  }
}

dependencies {
    //增加
    implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
}

我使用了其他版本的SpringBoot,如何查到配置方式?
这里建议使用https://start.spring.io进行自定义查询(无需梯子)


使用方式说明:
打开链接后如下图显示,Project选择自己的项目配置方式,SpringBoot选择自己的版本,在Dependencies中添加OpenFeign,点击下方的EXPLORE即可看到自动生成的配置,非常方便
也可以用于查询其他依赖的引入方式


image.png

二、为Application添加注解

// 这里建议指定一下包路径
@EnableFeignClients(basePackages = "com.example.xxx.*")

三、添加Service

在application.properties中添加常量(也可以直接写到Service中)

app.feign.config.name=word-api
app.feign.config.url=https://www.mxnzp.com/api
@Service
@FeignClient(url = "${app.feign.config.url}", name = "${app.feign.config.name}", configuration = FeignClientProperties.FeignClientConfiguration.class)
public interface WordTestService {

    @RequestMapping(value = "/idiom/search", method = RequestMethod.GET)
    public String searchWord(@RequestParam("key") String key, @RequestParam String app_id, @RequestParam String app_secret);
}

四、在Controller中调用即可

@RestController
@RequestMapping("/hello")
public class TestController {

    @Autowired
    WordTestService service;

    @GetMapping("/getword")
    public String testGet() {
        return service.searchWord("一", "app_id", "app_secret");
    }
}

项目运行后访问localhost:8080/hello/getword即可访问。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容