WebClient与HTTPInterface远程调用对比

远程调用

API/SDK的区别:

1.WebClient

1.1创建与调用

创建WebClient非常简单:

  • webclientcreate0
  • webclient.create(string baseurl)

还可以使用webclient.builder0 配置更多参数项:

  • uribuilderfactory: 自定义uribuilderfactory, 定义baseurl.
  • defaulturivariables:默认uril变量。
  • defaultheader:每个请求默认头
  • defaultcookie:每个请求默认 cookie.
  • defaultrequest:consumer 自定义每个请求
  • filter:过滤client发送的每个请求
  • exchangestrategies:http 消息 reader/writer 自元 er 自定义。
  • clientconnector:http client库设置。

定义Weather服务类,定义weather方法

post请求需要定义body 根据不同的接口定义各自的请求参数以及请求头header

复制代码
public Mono<String> weather(String city){
    //远程调用api
    //创建webclient
    String baseurl = "http://apis.juhe.cn/simpleWeather/query?";
    WebClient client = WebClient.create();
    //定义发请求方式
    Map<String,String>map=new HashMap<>();
    map.put("city",city);
    Mono<String> mono = client.post().uri("http://apis.juhe.cn/simpleWeather/query?key=251518e073ef6c3c9504dd286c3f6a86&city={city}", map)
            .contentType(MediaType.APPLICATION_JSON)//定义响应内容类型
            .header("User-Agent", "ikun")
            .retrieve()
            .bodyToMono(String.class);

    return mono;
}

在Controller类中返回数据

复制代码
//调用外部api获取天气
@GetMapping("weather")
public Mono<String> weather(@RequestParam(value = "city") String city){

    Mono<String> weather = weatherService.weather(city);
    return weather;
}

2.HTTP Interface

2.1导入依赖

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

2.2定义接口

复制代码
public interface WeatherInterface {

    @GetExchange(url = "/query",accept = "application/json")
    public Mono<String> getweather(@RequestParam("city") String city,
    @RequestParam String key);
}

public Mono<String> weather2(String city){
    //创建客户端
    WebClient client = WebClient.builder().baseUrl("http://apis.juhe.cn/simpleWeather")
            .codecs(clientCodecConfigurer -> {
                clientCodecConfigurer.defaultCodecs().maxInMemorySize(256*1024*1024);
            })
            .build();
    //创建工厂
    HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();

    //获取代理对象
    WeatherInterface weatherapi = factory.createClient(WeatherInterface.class);
    Mono<String> getweather = weatherapi.getweather(city,"251518e073ef6c3c9504dd286c3f6a86");
    return getweather;

}

从配置文件中取值 ${key}

2.3封装接口配置

复制代码
@Configuration
public class WebApiConfig {
    @Bean
    HttpServiceProxyFactory httpServiceProxyFactory(){
        //创建客户端
        WebClient client = WebClient.builder().baseUrl("http://apis.juhe.cn")
                .defaultHeader("user-agent","ikun") //定义默认请求头
                .codecs(clientCodecConfigurer -> {
                    clientCodecConfigurer.defaultCodecs().maxInMemorySize(256*1024*1024);
                })
                .build();
        //创建工厂
        HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();
        return factory;
    }
    @Bean
    WeatherInterface weatherInterface(){
        WeatherInterface weatherInterface = httpServiceProxyFactory().createClient(WeatherInterface.class);
        return weatherInterface;
    }

}

weatherservice里可以自动装配WeatherInterface调用

复制代码
@Autowired
private WeatherInterface weatherInterface;

public Mono<String> weather2(String city, @Value("${apikey}")String key){

    Mono<String> getweather = weatherInterface.getweather(city,key);
    return getweather;

}
相关推荐
算法与双吉汉堡1 分钟前
【短链接项目笔记】Day3 用户模块剩余部分
java·redis·后端
Chengbei112 分钟前
fastjson 原生反序列化配合动态代理绕过限制
java·安全·网络安全·系统安全·安全架构
lhrimperial3 分钟前
MySQL底层原理
java·后端·mysql
qq_377112374 分钟前
JAVA的平凡之路——此峰乃是最高峰JVM-GC垃圾回收器(1)-06
java·开发语言·jvm
学编程就要猛7 分钟前
算法:2.复写零
java·数据结构·算法
熊猫吃竹子9 分钟前
JVM G1GC参数调优实战
jvm·后端
我认不到你9 分钟前
paxos一致性算法(大白话+图解)
分布式·后端
文心快码BaiduComate10 分钟前
插件开发实录:我用Comate在VS Code里造了一场“能被代码融化”的初雪
前端·后端·前端框架
韩立学长11 分钟前
【开题答辩实录分享】以《植物园信息管理系统》为例进行选题答辩实录分享
java·数据库·spring
嘻哈baby11 分钟前
记一次线上OOM排查,JVM调优全过程
java