一吸重、為SpringBoot項(xiàng)目添加依賴
由于SpringBoot版本和OpenFeign版本有對(duì)應(yīng)關(guān)系醉者,這里要根據(jù)自己使用的SpringBoot版本來(lái)確定如何引入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 |
舉例:對(duì)于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)行自定義查詢(無(wú)需梯子)
使用方式說(shuō)明:
打開(kāi)鏈接后如下圖顯示溯祸,Project選擇自己的項(xiàng)目配置方式肢专,SpringBoot選擇自己的版本舞肆,在Dependencies中添加OpenFeign焦辅,點(diǎn)擊下方的EXPLORE即可看到自動(dòng)生成的配置,非常方便
也可以用于查詢其他依賴的引入方式
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)行后訪問(wèn)localhost:8080/hello/getword即可訪問(wèn)哩盲。