HTTP Interface
-
Spring 允许我们通过定义接口的方式,给任意位置发送 http 请求,实现远程调用,可以用来简化 HTTP 远程访问。需要webflux场景才可
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
-
定义接口
public interface BingService { @GetExchange(url = "/search",accept="application/json")//请求的地址,接收json数据 Mono<String> search(@RequestParam("area") String keyword, @RequsetHeader("Authorization") String auth);//在service里@GetExchange表示我要发一个请求参数叫"area" //和controller上不一样. }
-
创建代理&测试
@SpringBootTest class Boot05TaskApplicationTests { @Test public Mono<String> weather(String city) { //1、创建客户端 WebClient client = WebClient.builder() .baseUrl("https://cn.bing.com")//给哪发请求 .codecs(clientCodecConfigurer -> { clientCodecConfigurer .defaultCodecs() .maxInMemorySize(256*1024*1024); //响应数据量太大有可能会超出BufferSize,所以这里设置的大一点 }) .build(); //2、创建工厂 HttpServiceProxyFactory factory = HttpServiceProxyFactory .builder(WebClientAdapter.forClient(client)).build(); //3、获取代理对象 BingService bingService = factory.createClient(BingService.class);//BingService.class接口名 //4、测试调用 Mono<String> search = bingService.search(city,"APPCODE XXXXXXXX"); return weather; } }
-
生产模式----编写配置类config/WeatherConfiguration,@config
@Bean WeatherInterface WeatherInterface(){ //1、创建客户端 WebClient client = WebClient.builder() .baseUrl("https://cn.bing.com")//给哪发请求 .codecs(clientCodecConfigurer -> { clientCodecConfigurer .defaultCodecs() .maxInMemorySize(256*1024*1024); //响应数据量太大有可能会超出BufferSize,所以这里设置的大一点 }) .build(); //2、创建工厂 HttpServiceProxyFactory factory = HttpServiceProxyFactory .builder(WebClientAdapter.forClient(client)).build(); //3、获取代理对象 WeatherInterface WeatherInterface = factory.createClient(WeatherInterface.class);//BingService.class接口名 return WeatherInterface; }
-
WeatherService
@Autowired WeatherInterface WeatherInterface //4、测试调用 Mono<String> weather = WeatherInterface.search(city,"APPCODE XXXXXXXX"); return weather;