遠程調用--Http Interface
- 前言
- 1、導入依賴
- 2、定義接口
- 3 創建代理&測試
- 4、創建成配置變量
前言
這個功能是spring boot6提供的新功能,spring允許我們通過自定義接口的方式,給任意位置發送http請求,實現遠程調用,可以用來簡化http遠程訪問,需要webflux場景才可以
1、導入依賴
2、定義接口
package com.atguigu.boot305ssm.service;import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.service.annotation.GetExchange;/*** @author jitwxs* @date 2024年03月03日 20:39*/
public interface WeatherInterface {@GetExchange(url="/接口的后半截數據",accept = "application/json")String getWeather(@RequestParam("area") String city,@RequestHeader("Authorization") String auth);
}
3 創建代理&測試
public Mono<Mono<String>> weather(String city){
// 創建客戶端WebClient client = WebClient.builder().baseUrl("要請求的接口").codecs(clientCodecConfigurer -> {clientCodecConfigurer.defaultCodecs().maxInMemorySize(256*1024*1024);
// 響應數據兩太大有可能會超過bufferSize,所以這里設置的大一些}).build();
// 創建工廠HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();// 獲取代理對象WeatherInterface weatherAPI = factory.createClient(WeatherInterface.class);Mono<String> weather = weatherAPI.getWeather("西安","APPCODE 93b7e19861a24c519a7548b17dc46d75");return Mono.just(weather);}
4、創建成配置變量