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. git 学习笔记 —— 保留/丢弃当前分支修改并切换至其他分支

    笔者在本地终端进行 git 工作目录的相关处理时,遇到由于某种情况需要使用 git checkout 命令切换到其他分支的情景.此时,若已经对当前分支做了一定的修改,则直接切换分支时 git 会提示错 ...

  2. ASP.NET 内容管理系统CMS

    一.Umbraco 项目地址: http://umbraco.org/ Umbraco是一个开放源码的CMS内容管理系统,基于asp.net建立,使用mssql进行存储数据. 使用Umbraco ,设 ...

  3. JMeter基础【第六篇】JMeter5.1事务、检查点、集合点、思考时间、其余设置等

    JMeter5.1事务.检查点.集合点.思考时间.其余设置等

  4. pandas IO

    pd.read_csv("../data/user_info.csv", index_col="name") #假设csv里包含这几列: name, age, ...

  5. windows使用 xxx.bat运行相关指令

    今日思语:成人的世界,请停止低层次的忙碌 一般是windows上需要执行一些支持的命令时,我们一般都会直接使用控制台去操作,对于需要频繁操作的指令来说,使用控制台略显有些不便,比如不小心关闭后控制台后 ...

  6. [React] Fix "React Error: Rendered fewer hooks than expected"

    In this lesson we'll see an interesting situation where we're actually calling a function component ...

  7. Micro Benchmark Framework java 基准测试类库

    Micro Benchmark Framework 框架主要是method 层面上的 benchmark,精度可以精确到微秒级 比较典型的使用场景还有: 想定量地知道某个函数需要执行多长时间,以及执行 ...

  8. su与su -,sudo 的区别

    "sudo" , "su" , "su - " 区别: 一.sudo是一种权限管理机制,依赖于/etc/sudoers,其定义了授权给哪个用 ...

  9. python 判断元素是否在一个列表中

    import random val= data=[,,,,] : find=False val=int(input('请输入查找键值(1-9),输入-1离开:')) for i in data: if ...

  10. PHP系列 | [转] PHP中被忽略的性能优化利器:生成器

    官方:https://www.php.net/manual/zh/language.generators.overview.php 原文:https://segmentfault.com/a/1190 ...