Spring5中WebClient怎么用

发布时间:2021-09-23 15:17:53 作者:小新
来源:亿速云 阅读:123

这篇文章将为大家详细讲解有关Spring5中WebClient怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

前言

Spring5带来了新的响应式web开发框架WebFlux,同时,也引入了新的HttpClient框架WebClient。WebClient是Spring5中引入的执行 HTTP 请求的非阻塞、反应式客户端。它对同步和异步以及流方案都有很好的支持,WebClient发布后,RestTemplate将在将来版本中弃用,并且不会向前添加主要新功能。

WebClient与RestTemplate比较

WebClient是一个功能完善的Http请求客户端,与RestTemplate相比,WebClient支持以下内容:

非阻塞 I/O。  反应流背压(消费者消费负载过高时主动反馈生产者放慢生产速度的一种机制)。  具有高并发性,硬件资源消耗更少。  流畅的API设计。  同步和异步交互。  流式传输支持

HTTP底层库选择

Spring5的WebClient客户端和WebFlux服务器都依赖于相同的非阻塞编解码器来编码和解码请求和响应内容。默认底层使用Netty,内置支持Jetty反应性HttpClient实现。同时,也可以通过编码的方式实现ClientHttpConnector接口自定义新的底层库;如切换Jetty实现:

WebClient.builder()        .clientConnector(new JettyClientHttpConnector())        .build();

WebClient配置

基础配置

WebClient实例构造器可以设置一些基础的全局的web请求配置信息,比如默认的cookie、header、baseUrl等

WebClient.builder()        .defaultCookie("kl","kl")        .defaultUriVariables(ImmutableMap.of("name","kl"))        .defaultHeader("header","kl")        .defaultHeaders(httpHeaders -> {          httpHeaders.add("header1","kl");          httpHeaders.add("header2","kl");        })        .defaultCookies(cookie ->{          cookie.add("cookie1","kl");          cookie.add("cookie2","kl");        })        .baseUrl("http://www.kailing.pub")        .build();

Netty库配置

通过定制Netty底层库,可以配置SSl安全连接,以及请求超时,读写超时等

HttpClient httpClient = HttpClient.create()        .secure(sslContextSpec -> {          SslContextBuilder sslContextBuilder = SslContextBuilder.forClient()              .trustManager(new File("E://server.truststore"));          sslContextSpec.sslContext(sslContextBuilder);        }).tcpConfiguration(tcpClient -> {          tcpClient.doOnConnected(connection ->              //读写超时设置              connection.addHandlerLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS))                  .addHandlerLast(new WriteTimeoutHandler(10))          );          //连接超时设置          tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)          .option(ChannelOption.TCP_NODELAY,true);          return tcpClient;        });    WebClient.builder()        .clientConnector(new ReactorClientHttpConnector(httpClient))        .build();

编解码配置

针对特定的数据交互格式,可以设置自定义编解码的模式,如下:

ExchangeStrategies strategies = ExchangeStrategies.builder()        .codecs(configurer -> {          configurer.customCodecs().decoder(new Jackson2JsonDecoder());          configurer.customCodecs().encoder(new Jackson2JsonEncoder());        })        .build();    WebClient.builder()        .exchangeStrategies(strategies)        .build();

get请求示例

uri构造时支持属性占位符,真实参数在入参时排序好就可以。同时可以通过accept设置媒体类型,以及编码。最终的结果值是通过Mono和Flux来接收的,在subscribe方法中订阅返回值。

WebClient client = WebClient.create("http://www.kailing.pub");    Mono<String> result = client.get()        .uri("/article/index/arcid/{id}.html", 256)        .attributes(attr -> {          attr.put("name", "kl");          attr.put("age", "28");        })        .acceptCharset(StandardCharsets.UTF_8)        .accept(MediaType.TEXT_HTML)        .retrieve()        .bodyToMono(String.class);    result.subscribe(System.err::println);

post请求示例

post请求示例演示了一个比较复杂的场景,同时包含表单参数和文件流数据。如果是普通post请求,直接通过bodyValue设置对象实例即可。不用FormInserter构造。

WebClient client = WebClient.create("http://www.kailing.pub");    FormInserter formInserter = fromMultipartData("name","kl")        .with("age",19)        .with("map",ImmutableMap.of("xx","xx"))        .with("file",new File("E://xxx.doc"));    Mono<String> result = client.post()        .uri("/article/index/arcid/{id}.html", 256)        .contentType(MediaType.APPLICATION_JSON)        .body(formInserter)        //.bodyValue(ImmutableMap.of("name","kl"))        .retrieve()        .bodyToMono(String.class);    result.subscribe(System.err::println);

同步返回结果

上面演示的都是异步的通过mono的subscribe订阅响应值。当然,如果你想同步阻塞获取结果,也可以通过.block()阻塞当前线程获取返回值。

WebClient client = WebClient.create("http://www.kailing.pub");   String result = client .get()        .uri("/article/index/arcid/{id}.html", 256)        .retrieve()        .bodyToMono(String.class)        .block();    System.err.println(result);

但是,如果需要进行多个调用,则更高效地方式是避免单独阻塞每个响应,而是等待组合结果,如:

WebClient client = WebClient.create("http://www.kailing.pub");    Mono<String> result1Mono = client .get()        .uri("/article/index/arcid/{id}.html", 255)        .retrieve()        .bodyToMono(String.class);    Mono<String> result2Mono = client .get()        .uri("/article/index/arcid/{id}.html", 254)        .retrieve()        .bodyToMono(String.class);    Map<String,String> map = Mono.zip(result1Mono, result2Mono, (result1, result2) -> {      Map<String, String> arrayList = new HashMap<>();      arrayList.put("result1", result1);      arrayList.put("result2", result2);      return arrayList;    }).block();    System.err.println(map.toString());

Filter过滤器

可以通过设置filter拦截器,统一修改拦截请求,比如认证的场景,如下示例,filter注册单个拦截器,filters可以注册多个拦截器,basicAuthentication是系统内置的用于basicAuth的拦截器,limitResponseSize是系统内置用于限制响值byte大小的拦截器

WebClient.builder()        .baseUrl("http://www.kailing.pub")        .filter((request, next) -> {          ClientRequest filtered = ClientRequest.from(request)              .header("foo", "bar")              .build();          return next.exchange(filtered);        })        .filters(filters ->{          filters.add(ExchangeFilterFunctions.basicAuthentication("username","password"));          filters.add(ExchangeFilterFunctions.limitResponseSize(800));        })        .build().get()        .uri("/article/index/arcid/{id}.html", 254)        .retrieve()        .bodyToMono(String.class)        .subscribe(System.err::println);

websocket支持

WebClient不支持websocket请求,请求websocket接口时需要使用WebSocketClient,如:

WebSocketClient client = new ReactorNettyWebSocketClient();URI url = new URI("ws://localhost:8080/path");client.execute(url, session ->    session.receive()        .doOnNext(System.out::println)        .then());

关于“Spring5中WebClient怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. Spring WebClient vs. RestTemplate
  2. WebClient怎么在Spring5中使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring5 webclient

上一篇:如何使用SurfaceView实现视频弹幕

下一篇:提升电脑性能和优化电脑系统的操作方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》