WebClient的请求模式属于异步非阻塞,能够以少量固定的线程处理高并发的HTTP请求

WebClient是Spring WebFlux模块提供的一个非阻塞的基于响应式编程的进行Http请求的客户端工具,从Spring5.0开始提供

在Spring Boot应用中

1.添加Spring WebFlux依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

2.使用

(1)Restful接口demoController.java

package com.example.demo.controller;

import com.example.demo.domain.MyData;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest; @RestController
@RequestMapping("/api")
public class demoController { @GetMapping(value = "/getHeader", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public MyData getHeader(HttpServletRequest request) { int id = 0;
if (request.getParameter("id") != null) {
id = Integer.valueOf(request.getParameter("id"));
}
String name = request.getParameter("name");
//header
String userAgent = "USER_AGENT——" + request.getHeader(HttpHeaders.USER_AGENT);
userAgent += " | ACCEPT_CHARSET——" + request.getHeader(HttpHeaders.ACCEPT_CHARSET);
userAgent += " | ACCEPT_ENCODING——" + request.getHeader(HttpHeaders.ACCEPT_ENCODING);
userAgent += " | ContextPath——" + request.getContextPath();
userAgent += " | AuthType——" + request.getAuthType();
userAgent += " | PathInfo——" + request.getPathInfo();
userAgent += " | Method——" + request.getMethod();
userAgent += " | QueryString——" + request.getQueryString();
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() + ":" + cookie.getValue());
}
}
MyData data = new MyData();
data.setId(id);
data.setName(name);
data.setOther(userAgent);
return data;
} @PostMapping(value = "/getPost", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public MyData getPost(HttpServletRequest request) { int id = 0;
if (request.getParameter("id") != null) {
id = Integer.valueOf(request.getParameter("id"));
}
String name = request.getParameter("name");
System.out.println(name + "," + id);
MyData data = new MyData();
data.setId(id);
data.setName(name);
return data; } /**
* POST传JSON请求
*/
@PostMapping(value = "/getPostJson", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public MyData getPostJson(@RequestBody(required = true) MyData data) {
System.out.println(data.getId());
System.out.println(data.getName());
return data;
}
}

MyData.java

package com.example.demo.domain;

public class MyData {
private int id;
private String name;
private String other;
public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getOther() {
return other;
} public void setOther(String other) {
this.other = other;
}
}

(2)WebClient使用

DemoApplicationTests.java

package com.example.demo;

import com.example.demo.domain.MyData;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono; import java.time.Duration;
import java.time.temporal.ChronoUnit; public class DemoApplicationTests { private WebClient webClient = WebClient.builder()
.baseUrl("http://127.0.0.1:8080")
.defaultHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)")
.defaultCookie("ACCESS_TOKEN", "test_token").build(); @Test
public void WebGetDemo() { try {
Mono<MyData> resp = webClient.method(HttpMethod.GET).uri("api/getHeader?id={id}&name={name}", 123, "abc")
.retrieve()
.bodyToMono(MyData.class);
MyData data = resp.block();
System.out.println("WebGetDemo result----- " + data.getString());
} catch (Exception e) {
e.printStackTrace();
} } @Test
public void WebPostDemo() {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(2);
formData.add("id", "456");
formData.add("name", "xyz"); Mono<MyData> response = webClient.method(HttpMethod.POST).uri("/api/getPost")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData))
.retrieve()
.bodyToMono(MyData.class).timeout(Duration.of(10, ChronoUnit.SECONDS));
System.out.println(response);
MyData data = response.block();
System.out.println("WebPostDemo result----- " + data.getString());
} @Test
public void WebPostJson() {
MyData requestData = new MyData();
requestData.setId(789);
requestData.setName("lmn"); Mono<MyData> response = webClient.post().uri("/api/getPostJson")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.syncBody(requestData)
.retrieve()
.bodyToMono(MyData.class).timeout(Duration.of(10, ChronoUnit.SECONDS)); MyData data = response.block();
System.out.println("WebPostJson result----- " + data.getString());
} }

spring boot使用WebClient调用其他系统提供的HTTP服务的更多相关文章

  1. 精尽Spring Boot源码分析 - 日志系统

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  2. Spring Boot 异步方法的调用

    Spring Boot 异步方法的调用 参考资料: 1.Spring Boot中使用@Async实现异步调用 使用方法 两个步骤: 1.开启配置 @EnableAsync,这一步特别容易忘记,导致测试 ...

  3. Spring Boot + Dubbo 可运行的例子源码-实现服务注册和远程调用

    最近公司的一个分布式系统想要尝试迁移到Dubbo,项目本身是Spring Boot的,经过一些努力,最终也算是搭建起一个基础的框架了,放到这里记录一下.需要依赖一个外部的zookeeper. 源码地址 ...

  4. Spring Boot发布和调用RESTful web service

    Spring Boot可以非常简单的发布和调用RESTful web service,下面参考官方指导体验一下 1.首先访问 http://start.spring.io/ 生成Spring Boot ...

  5. 17、Spring Boot普通类调用bean【从零开始学Spring Boot】

    转载:http://blog.csdn.net/linxingliang/article/details/52013017 我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个 ...

  6. (17)Spring Boot普通类调用bean【从零开始学Spring Boot】

    我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的Java类中,想直接使用 ...

  7. spring boot 并发请求,其他系统接口,丢失request的header信息【多线程、线程池、@Async 】

    场景:一次迭代在灰度环境发版时,测试反馈说我开发的那个功能,查询接口有部分字段数据是空的,后续排查日志,发现日志如下: feign.RetryableException: cannot retry d ...

  8. Spring Boot普通类调用bean

    1 在Spring Boot可以扫描的包下 假设我们编写的工具类为SpringUtil. 如果我们编写的SpringUtil在Spring Boot可以扫描的包下或者使用@ComponentScan引 ...

  9. Spring Boot 使用 CXF 调用 WebService 服务

    上一张我们讲到 Spring Boot 开发 WebService 服务,本章研究基于 CXF 调用 WebService.另外本来想写一篇 xfire 作为 client 端来调用 webservi ...

随机推荐

  1. jmeter5.1企业级应用功能详解

    apache jmeter是100%的java桌面应用程序,它被设计用来加载被测试软件功能特性.度量被测试软件的性能.jmeter可以模拟大量的服务器负载,并且jmeter提供图形化的性能分析. JM ...

  2. [Algorithm] Bitwise Operators

    "|" can be used as assign "&" can be used as check // Read, Write, Execute / ...

  3. LOJ P10249 weight 题解

    每日一题 day58 打卡 Analysis 这道题搜索的想法非常巧妙,从两端向中间找,这样可以保证仅仅对于head或tail而言,需要用到的前缀和与后缀和是单调递增的,这样排个序就解决了. 值得一提 ...

  4. ubuntu及Cenos国内镜像下载

    打开:https://man.linuxde.net/download/ CentOS 7提供了三种ISO镜像文件的下载: DVD ISO 标准安装版,一般下载这个就可以了(推荐) Everythin ...

  5. Linux 检测 tls

    检测 tls # openssl s_client -connect intl.jdair.net: -tls1

  6. 字符串Hash学习笔记

    [toc] # 以下内容作废,太多错误了,等我有时间重写 说一下什么是Hash,说白了就是把一大坨字符用一些神奇的数来表示,可以说是把字符加密了. 简单一点就是一个像函数一样的东西,你放进去一个值,它 ...

  7. 关于wineQQ8.9.19983deepin23版本提升不能在使用请升级,Linux偷懒升级方法

    安装wineQQ8.9.19983deepin23版本后提示,不在提供服务请升级. 第一步 前往QQ官方下载Windows最先版本QQ https://qd.myapp.com/myapp/qqtea ...

  8. charles安装及使用

    一.下载安装charles 1.官方网址:https://www.charlesproxy.com/ 选择自己需要的macos/windows/linux下对应的最新版本安装即可 我的是mac,下载版 ...

  9. Mongoose 两个表关联查询aggregate 以及 Mongoose中获取ObjectId

    Mongoose 两个表关联查询aggregate 通常两个表关联查询的时候,是一种一对多的关系,比如订单与订单详情就是一对多的关系,一个订单下面有多个商品 数据模拟 首先我们先将数据模拟出来,先选择 ...

  10. 安装tensorflow-gpu2.0(windows)

    anaconda安装见前一篇https://www.cnblogs.com/wintersoft/p/11609188.html https://mirrors.tuna.tsinghua.edu.c ...