OpenFeign做錯了什么,慘遭SpringCloud 2022拋棄!
Feign是Spring Cloud中的一個聲明式的HTTP客戶端庫,用于簡化編寫基于HTTP的服務調用代碼。但是從Spring Cloud 2020版本開始,官方宣布Feign將不再維護和支持,推薦使用OpenFeign作為替代方案。
但是,隨著SpringCloud 2022的發布,官方宣布OpenFeign將被視為功能完整。這意味著Spring Cloud團隊將不再向模塊添加新特性。只會修復bug和安全問題。
其實,之所以OpenFeign后期不再更新,主要是因為在Spring 6.0 發布之后,Spring內置了一個HTTP客戶端——@HttpExchange ,而官方肯定建議大家使用這個自帶客戶端進行HTTP調用。
那么,@HttpExchange怎么使用呢?下面是一個小例子,大家可以簡單體驗一下。
想要使用這個新的HTTP客戶端,需要Spring升級到6.0,或者SpringBoot升級到3.0版本,然后再在POM中依賴spring-web。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
在 Spring 6.0中,可以讓HTTP 服務接口帶有@HttpExchange。那么這個接口方法就會被視為 HTTP 端點,目前支持的注解有以下幾個:
- @GetExchange HTTP GET 請求
- @PostExchange HTTP POST 請求
- @PutExchange HTTP PUT 請求
- @PatchExchange HTTP PATCH 請求
- @DelectExchange HTTP DELETE 請求
- 本文節選自我的Java面試寶典
首先,我們自己定義一個HTTP接口,定義一個實體類:
/**
* @Author Hollis
** /
public class User implements Serializable {
private String name;
private Integer age;
// Constructor、Getter、Setter
@Override
public String toString() {
return name + ":" + age;
}
}
然后定義一個Controller。
@GetMapping("/users")
public List<User> list() {
return IntStream.rangeClosed(20, 25)
.mapToObj(i -> new User("Hollis", i))
.collect(Collectors.toList());
}
以上,服務在啟動后,通過http://localhost:8080/users地址訪問后會得到10個我生成的用戶信息。
有了一個HTTP接口之后,用@HttpExchange 調用方式如下:
@GetExchange("/users")
List<User> getUsers();
}
還需要定義一個用于HTTP調用的client:
public class WebConfiguration {
@Bean
public WebClient webClient() {
return WebClient.builder()
.baseUrl("https://localhost:8080")
.build();
}
@Bean
UserApiService userApiService(){
HttpServiceProxyFactory httpServiceProxyFactory =
HttpServiceProxyFactory.builder(WebClientAdapter.forClient(webClient()))
.build();
return httpServiceProxyFactory.createClient(UserApiService.class);
}
}
然后就可以調用了,如:
@SpringBootTest
class UsersTests {
@Autowired
private UserApiService userApiService;
@Test
public void testGetUsers(){
List<User> users = userApiService.getUsers();
Assert.assertEquals(users.size(),10);
}
}
以上,就是在Spring 6.0中,使用Spring自帶的@HttpExchange實現HTTP調用的例子,看起來還是比較容易使用的。
你覺得好嗎?愿意使用他代替OpenFeign嗎?當然,前提是要升級到Spring 6.0 ,這個還有個前提就是要升級到Java 17......