SpringBoot3 響應(yīng)式網(wǎng)絡(luò)請求客戶端的實現(xiàn)
SpringBoot是一個基于Spring的快速開發(fā)框架,它可以幫助我們快速構(gòu)建、部署和運行Java應(yīng)用程序。HTTP接口是Web應(yīng)用程序與外部系統(tǒng)進行通信的一種方式,通過HTTP協(xié)議,我們可以實現(xiàn)客戶端與服務(wù)器之間的數(shù)據(jù)交互。
SpringBoot 整合提供了很多方式進行遠程調(diào)用
- 輕量級客戶端方式
RestTemplate
: 普通開發(fā)WebClient
: 響應(yīng)式編程開發(fā)Http Interface
: 聲明式編程
在 Spring WebFlux 中,Mono 和 Flux 都是響應(yīng)式編程的工具,用于處理異步數(shù)據(jù)流。
Mono
: 是一個單例的、不可變的、最終的、完成的、包含單個元素的數(shù)據(jù)流,它只能發(fā)出一個元素。
Flux
: 是一個可變的、無限的、最終的、未完成的數(shù)據(jù)流,它可以發(fā)出任意數(shù)量的元素。
聲明式客戶端
聲明式 http 客戶端主旨是使得編寫 java http 客戶端更容易。為了貫徹這個理念,采用了通過處理注解來自動生成請求的方式(官方稱呼為聲明式、模板化)。通過聲明式 http 客戶端實現(xiàn)我們就可以在 java 中像調(diào)用一個本地方法一樣完成一次 http 請求,大大減少了編碼成本,同時提高了代碼可讀性。
測試環(huán)境
SpringBoot3.0.6,JDK17
1. WebClient
WebClient 是Spring WebFlux 模塊提供的一個非阻塞的基于響應(yīng)式編程的進行 Http 請求的客戶端工具。完全非阻塞,支持流式處理。
1.1 創(chuàng)建與配置
發(fā)請求:
- 請求方式: GET\POST\DELETE…
- 請求路徑: /…
- 請求參數(shù):aa=bb&cc=dd&xxx
- 請求頭: aa=bb,cc=ddd
- 請求體:
創(chuàng)建WebClient
: WebClient.create()
WebClient.create(String baseUrl)
使用WebClient.builder()
配置更多參數(shù):uriBuilderFactory
: 自定義UriBuilderFactory
,定義 baseurl.defaultUriVariables
: 默認 uri 變量.defaultHeader
: 每個請求默認頭.defaultCookie
: 每個請求默認 cookie.defaultRequest
: Consumer 自定義每個請求.filter
: 過濾 client 發(fā)送的每個請求exchangeStrategies
: HTTP 消息 reader/writer 自定義.clientConnector
: HTTP client 庫設(shè)置.
pom依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
WebClient webClient = WebClient.create("https://api.qqsuu.cn");
1.2 獲取響應(yīng)
retrieve()
方法用來聲明如何提取響應(yīng)數(shù)據(jù)。比如
//獲取響應(yīng)完整信息 WebClient client = WebClient.create("https://example.org"); Mono<ResponseEntity<Person>> result = client.get() .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) .retrieve() .toEntity(Person.class); //只獲取body WebClient client = WebClient.create("https://example.org"); Mono<Person> result = client.get() .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(Person.class); //stream數(shù)據(jù) Flux<Quote> result = client.get() .uri("/quotes").accept(MediaType.TEXT_EVENT_STREAM) .retrieve() .bodyToFlux(Quote.class); //定義錯誤處理 Mono<Person> result = client.get() .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) .retrieve() .onStatus(HttpStatus::is4xxClientError, response -> ...) .onStatus(HttpStatus::is5xxServerError, response -> ...) .bodyToMono(Person.class);
1.3 定義請求體
//1、響應(yīng)式-單個數(shù)據(jù) Mono<Person> personMono = ... ; Mono<Void> result = client.post() .uri("/persons/{id}", id) .contentType(MediaType.APPLICATION_JSON) .body(personMono, Person.class) .retrieve() .bodyToMono(Void.class); //2、響應(yīng)式-多個數(shù)據(jù) Flux<Person> personFlux = ... ; Mono<Void> result = client.post() .uri("/persons/{id}", id) .contentType(MediaType.APPLICATION_STREAM_JSON) .body(personFlux, Person.class) .retrieve() .bodyToMono(Void.class); //3、普通對象 Person person = ... ; Mono<Void> result = client.post() .uri("/persons/{id}", id) .contentType(MediaType.APPLICATION_JSON) .bodyValue(person) .retrieve() .bodyToMono(Void.class);
2. HTTP Interface
從 Spring 6 和 Spring Boot 3 開始,Spring 框架支持將遠程 HTTP 服務(wù)代理成帶有特定注解的 Java http interface。類似的庫,如 OpenFeign 和 Retrofit 仍然可以使用,但 http interface 為 Spring 框架添加內(nèi)置支持。
HTTP Interface可以將 HTTP 服務(wù)定義成一個包含特定注解標記的方法的 Java 接口,然后通過對接口方法的調(diào)用,完成 HTTP 請求。
2.1 定義接口
public interface BingService { @GetExchange(url = "/search") String search(@RequestParam("keyword") String keyword); }
2.2 創(chuàng)建代理&測試
@SpringBootTest class Boot05TaskApplicationTests { @Test void contextLoads() throws InterruptedException { //1、創(chuàng)建客戶端 WebClient client = WebClient.builder() .baseUrl("https://cn.bing.com") .codecs(clientCodecConfigurer -> { clientCodecConfigurer .defaultCodecs() .maxInMemorySize(256*1024*1024); //響應(yīng)數(shù)據(jù)量太大有可能會超出BufferSize,所以這里設(shè)置的大一點 }) .build(); //2、創(chuàng)建工廠 HttpServiceProxyFactory factory = HttpServiceProxyFactory .builder(WebClientAdapter.forClient(client)).build(); //3、獲取代理對象 BingService bingService = factory.createClient(BingService.class); //4、測試調(diào)用 Mono<String> search = bingService.search("chatgpt是什么"); System.out.println("=========="); //return search; search.subscribe(str -> System.out.println(str)); Thread.sleep(100000); } }
到此這篇關(guān)于SpringBoot3 響應(yīng)式網(wǎng)絡(luò)請求客戶端的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot3 網(wǎng)絡(luò)請求客戶端內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一篇文章帶你了解Java容器,面板及四大布局管理器應(yīng)用
這篇文章主要介紹了JAVA布局管理器與面板組合代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2021-08-08SpringBoot 并發(fā)登錄人數(shù)控制的實現(xiàn)方法
這篇文章主要介紹了SpringBoot 并發(fā)登錄人數(shù)控制的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05