spring?webClient配置及使用簡(jiǎn)單代碼示例
1.配置
import com.zty.common.util.WebUtils; import io.netty.channel.ChannelOption; import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.handler.timeout.WriteTimeoutHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient; import reactor.netty.http.client.HttpClient; import reactor.netty.resources.ConnectionProvider; import java.time.Duration; /** * WebClient配置 * @author zty */ @Slf4j @Configuration public class WebClientConfig { @Bean public WebClient webClient(){ //配置固定大小連接池 ConnectionProvider provider = ConnectionProvider .builder("custom") // 等待超時(shí)時(shí)間 .pendingAcquireTimeout(Duration.ofSeconds(10)) // 最大連接數(shù) .maxConnections(200) // 最大空閑時(shí)間 .maxIdleTime(Duration.ofSeconds(5)) // 最大等待連接數(shù)量 .pendingAcquireMaxCount(-1) .build(); /** * doOnBind 當(dāng)服務(wù)器channel即將被綁定的時(shí)候調(diào)用。 * doOnBound 當(dāng)服務(wù)器channel已經(jīng)被綁定的時(shí)候調(diào)用。 * doOnChannelInit 當(dāng)channel初始化的時(shí)候被調(diào)用。 * doOnConnection 當(dāng)一個(gè)遠(yuǎn)程客戶端連接上的時(shí)候被調(diào)用。 * doOnUnbound 當(dāng)服務(wù)器channel解綁的時(shí)候被調(diào)用。 */ HttpClient httpClient = HttpClient.create(provider) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 6000) .option(ChannelOption.SO_KEEPALIVE, true) .responseTimeout(Duration.ofSeconds(6)) .keepAlive(true) //連接成功 .doOnConnected(connection -> connection.addHandlerLast(new ReadTimeoutHandler(6)) .addHandlerLast(new WriteTimeoutHandler(6))) //每次請(qǐng)求后執(zhí)行flush,防止服務(wù)器主動(dòng)斷開連接 .doAfterRequest((httpClientRequest, connection) -> { connection.channel().alloc().buffer().release(); connection.channel().flush(); connection.channel().pipeline().flush(); }); return WebClient.builder() .baseUrl("http://127.0.0.1:8080") .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .defaultHeader(HttpHeaders.CONNECTION, "keep-alive") .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); } }
2.使用
import com.alibaba.fastjson2.JSON; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import java.util.HashMap; /** * http消息發(fā)送工具 * @author zty */ @Slf4j @Component public class WebUtils { @Autowired WebClient webClient; @Async public void post(HashMap<String, Object> message){ // 發(fā)送請(qǐng)求 webClient.post() // 請(qǐng)求路徑 .uri("/test") // 攜帶參數(shù) .bodyValue(JSON.toJSONString(message)) // 獲取響應(yīng)體 .retrieve() // 響應(yīng)數(shù)據(jù)類型轉(zhuǎn)換 .bodyToMono(String.class) .doOnError(throwable -> log.info(throwable.getMessage())) .onErrorResume(e -> Mono.just("Error " + e.getMessage())) // 異步 .subscribe(); } }
附:一個(gè)帶有多個(gè)查詢參數(shù)的WebClient使用示例
import org.springframework.web.reactive.function.client.WebClient; public class ExampleWebClient { public static void main(String[] args) { WebClient client = WebClient.create("https://api.example.com"); client.get() .uri(uriBuilder -> uriBuilder.path("/search") .queryParam("q", "WebClient") .queryParam("page", 1) .queryParam("size", 20) .build()) .retrieve() .bodyToMono(String.class) .subscribe(response -> System.out.println(response)); } }
在這個(gè)示例中,我們使用了uri()
方法來構(gòu)建URI。使用了一個(gè)Lambda表達(dá)式,在其中的uriBuilder
對(duì)象(UriBuilder
類型)中指定了路徑和查詢參數(shù)。在這個(gè)例子中,我們將/search
作為路徑,以及三個(gè)查詢參數(shù)q
、page
、size
來進(jìn)行搜索,它們的值依次為WebClient
(表示搜索關(guān)鍵字為WebClient
)、1
、20
。
最終的URI將會(huì)是一個(gè)類似于 https://api.example.com/search?q=WebClient&page=1&size=20
的字符串。在發(fā)送請(qǐng)求后,我們將響應(yīng)體轉(zhuǎn)換為String類型的Mono對(duì)象,并使用subscribe()
方法輸出響應(yīng)內(nèi)容。
總結(jié)
到此這篇關(guān)于spring webClient配置及使用的文章就介紹到這了,更多相關(guān)spring webClient配置使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue實(shí)現(xiàn)驗(yàn)證碼登錄的超詳細(xì)步驟
這篇文章主要給大家介紹了關(guān)于Vue實(shí)現(xiàn)驗(yàn)證碼登錄的超詳細(xì)步驟,我們?cè)谑褂胿ue進(jìn)行前端開發(fā)時(shí)都需要登錄驗(yàn)證,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09springboot項(xiàng)目攔截前端請(qǐng)求中的特殊字符串(解決方案)
springboot項(xiàng)目中,需要對(duì)前端請(qǐng)求數(shù)據(jù)進(jìn)行過濾,攔截特殊字符,本文通過實(shí)例代碼給大家分享完美解決方案,感興趣的朋友一起看看吧2023-10-10spring項(xiàng)目如何配置多數(shù)據(jù)源(已上生產(chǎn),親測(cè)有效)
這篇文章主要介紹了spring項(xiàng)目如何配置多數(shù)據(jù)源(已上生產(chǎn),親測(cè)有效),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12PowerJob的ServerDiscoveryService工作流程源碼解讀
這篇文章主要為大家介紹了PowerJob的ServerDiscoveryService工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12Java使用IOC控制反轉(zhuǎn)的三種設(shè)計(jì)模式詳解
這篇文章主要為大家詳細(xì)介紹了Java使用IOC控制反轉(zhuǎn)的三種設(shè)計(jì)模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10繼承WebMvcConfigurationSupport后自動(dòng)配置不生效及如何配置攔截器
這篇文章主要介紹了繼承WebMvcConfigurationSupport后自動(dòng)配置不生效及如何配置攔截器,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11