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

一、為SpringBoot項(xiàng)目添加依賴

由于SpringBoot版本和OpenFeign版本有對應(yīng)關(guān)系,這里要根據(jù)自己使用的SpringBoot版本來確定如何引入OpenFeign。


以下內(nèi)容取自官網(wǎng)

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進(jìn)行自定義查詢(無需梯子)


使用方式說明:
打開鏈接后如下圖顯示,Project選擇自己的項(xiàng)目配置方式,SpringBoot選擇自己的版本,在Dependencies中添加OpenFeign,點(diǎn)擊下方的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中調(diào)用即可

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

    @Autowired
    WordTestService service;

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

項(xiàng)目運(yùn)行后訪問localhost:8080/hello/getword即可訪問。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容