來吧,會用就行具體理論不討論
1、首先pom.xml引入webflux依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
別問為什么因為是響應式.......都說不管理論了,繼續?
2、創建WebClientController控制器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.atguigu.boot3_07_http.service.WebClientService;@RestController
public class WebClientController {@Autowiredprivate WebClientService webClientService;// 等下創建真正干活的service類/*** 博主這里對接的是華為云的人臉API獲取token的測試,用什么api測試都是大同小異的* WebClient * @param authWrapper 請求體消息,有華為云要的key,id,scecc,password,name啥啥的,根據自己的api要求來就行* @return*/
@PostMapping("/huawei")public Mono<String> huawei(@RequestBody(required = false) AuthWrapper authWrapper) {if (authWrapper == null) {return Mono.just("請求體不能為空"); // 返回錯誤信息}return webClientService.webClient("https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens", authWrapper) //這里放接口地址和參數,當然authWrapper實際項目是從數據庫拿的.onErrorResume(e -> {// 處理其他可能的異常return Mono.just("發生錯誤:" + e.getMessage());});}}
3、創建打工仔程序員WebClientService 類
import com.atguigu.boot3_07_http.entity.AuthWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;@Service
public class WebClientService {public Mono<String> webClient(String url, AuthWrapper authWrapper) {//遠程調用//1、創建WebClientWebClient client = WebClient.create();//2.編輯請求return client.post().uri(url)// .contentType(MediaType.APPLICATION_JSON) //和.header()一樣的不用重復,推薦用.header自定義頭部.bodyValue(authWrapper) //請求體參數.header("Content-Type", "application/json") //Content-Type字段,json格式,具體看api有要求請求頭不.retrieve()//.bodyToMono(String.class) // 獲取響應體的JSON數據并轉換為String類型的Mono對象.toBodilessEntity() // 應為博主測試的api返回的是響應頭,所有不關注響應體.map(response -> {String token = response.getHeaders().getFirst("X-Subject-Token");//獲取字段X-Subject-Token響應頭消息if (token == null) {// 不拋出異常,而是返回錯誤信息return "錯誤:未獲取到華為云Token";}return token;//或者if去掉,用Objects.requireNonNullElse() //對象不為空輸出:參數1,為空輸出:參數2
// return Objects.requireNonNullElse(token, "錯誤:未獲取到華為云Token");});}}
最后看下返回結果,華為云返回的token
好啦,WebClient遠程調用非阻塞、響應式HTTP客戶端
最后大家有沒有覺得,比RestTemplate傳統的方便很多,但是沒有實現高可用,有新的請求還有要搞一堆,我們使用?Http Interface: 聲明式編程(官方推薦,也是很多大型項目的用法),并且創建工廠接口,這樣只用寫一次,以后需要的不用api可用直接調用,我也同時更新出來了