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個我生成的使用者資訊。(Java後端面試寶典,60多萬字,600多道常考面試題,吊打面試官)
有了一個HTTP接口之後,用@HttpExchange 調用方式如下:
public interface UserApiService { @GetExchange("/users")
List<User> getUsers();
}
還需要定義一個用于HTTP調用的client:
@Configurationpublic 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......
https://mp.weixin.qq.com/s/nTvtWtGaF4kNNZ20eyKAhA