欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot 3.0 新特性內(nèi)置聲明式HTTP客戶端實例詳解

 更新時間:2022年12月02日 10:55:47   投稿:mrr  
聲明式 http 客戶端主旨是使得編寫 java http 客戶端更容易,為了貫徹這個理念,采用了通過處理注解來自動生成請求的方式,本文給大家詳解介紹SpringBoot 聲明式HTTP客戶端相關知識,感興趣的朋友跟隨小編一起看看吧

http interface

從 Spring 6 和 Spring Boot 3 開始,Spring 框架支持將遠程 HTTP 服務代理成帶有特定注解的 Java http interface。類似的庫,如 OpenFeign 和 Retrofit 仍然可以使用,但 http interface 為 Spring 框架添加內(nèi)置支持。

什么是聲明式客戶端

聲明式 http 客戶端主旨是使得編寫 java http 客戶端更容易。為了貫徹這個理念,采用了通過處理注解來自動生成請求的方式(官方稱呼為聲明式、模板化)。通過聲明式 http 客戶端實現(xiàn)我們就可以在 java 中像調(diào)用一個本地方法一樣完成一次 http 請求,大大減少了編碼成本,同時提高了代碼可讀性。

舉個例子,如果想調(diào)用 /tenants 的接口,只需要定義如下的接口類即可

public interface TenantClient {

  @GetExchange("/tenants")
  Flux<User> getAll();
}

Spring 會在運行時提供接口的調(diào)用的具體實現(xiàn),如上請求我們可以如 Java 方法一樣調(diào)用

@Autowired
TenantClient tenantClient;

tenantClient.getAll().subscribe(

);

測試使用

1. maven 依賴

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- For webclient support -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

如下圖: 目前官方只提供了非阻塞 webclient 的 http interface 實現(xiàn),所以依賴中我們需要添加 webflux

2. 創(chuàng)建 Http interface 類型

需要再接口類上添加 @HttpExchange 聲明此類事 http interface 端點

@HttpExchange
public interface DemoApi {

    @GetExchange("/admin/tenant/list")
    String list();

方法上支持如下注解

@GetExchange:  for HTTP GET requests.
@PostExchange:  for HTTP POST requests.
@PutExchange: for HTTP PUT requests.
@DeleteExchange: for HTTP DELETE requests.
@PatchExchange:  for HTTP PATCH requests.

方法參數(shù)支持的注解

@PathVariable: 占位符參數(shù).
@RequestBody: 請求body.
@RequestParam: 請求參數(shù).
@RequestHeader: 請求頭.
@RequestPart: 表單請求.
@CookieValue: 請求cookie.

3. 注入聲明式客戶端

通過給 HttpServiceProxyFactory 注入攜帶目標接口 baseUrl 的的 webclient,實現(xiàn) webclient 和 http interface 的關聯(lián)

    @Bean
    DemoApi demoApi() {
        WebClient client = WebClient.builder().baseUrl("http://pigx.pigx.vip/").build();
        HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();
        return factory.createClient(DemoApi.class);
    }

4. 單元測試調(diào)用 http interface

@SpringBootTest
class DemoApplicationTests {
	@Autowired
	private DemoApi demoApi;

	@Test
	void testDemoApi() {
		demoApi.list();
	}
}

基于Spring Boot 2.7、 Spring Cloud 2021 & Alibaba、 SAS OAuth2 一個可支持企業(yè)各業(yè)務系統(tǒng)或產(chǎn)品快速開發(fā)實現(xiàn)的開源微服務應用開發(fā)平臺

到此這篇關于SpringBoot 3.0 新特性,內(nèi)置聲明式HTTP客戶端的文章就介紹到這了,更多相關SpringBoot 聲明式HTTP客戶端內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論