WebClient,HTTP Interface远程调用阿里云API

WebClient,HTTP Interface远程调用阿里云API_第1张图片

 HTTP Interface

  1. Spring 允许我们通过定义接口的方式,给任意位置发送 http 请求,实现远程调用,可以用来简化 HTTP 远程访问。需要webflux场景才可

    
        org.springframework.boot
        spring-boot-starter-webflux
    
  2. 定义接口

    public interface BingService {
    
        @GetExchange(url = "/search",accept="application/json")//请求的地址,接收json数据
        Mono search(@RequestParam("area") String keyword,
                        @RequsetHeader("Authorization") String auth);//在service里@GetExchange表示我要发一个请求参数叫"area"
    //和controller上不一样.
    }
  3. 创建代理&测试

    @SpringBootTest
    class Boot05TaskApplicationTests {
    
        @Test
        public Mono 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 search = bingService.search(city,"APPCODE XXXXXXXX");
            return weather;
    
        }
    
    }

  4. 生产模式----编写配置类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;
    }
  5. WeatherService

    @Autowired
    WeatherInterface WeatherInterface
    
    
    
    //4、测试调用
            Mono weather = WeatherInterface.search(city,"APPCODE XXXXXXXX");
            return weather;
    

你可能感兴趣的:(阿里云,云计算)