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. Angular vs React---React-ing to change

    这篇文章的全局观和思路一级棒! The Fairy Tale Cast your mind back to 2010 when users started to demand interactive ...

  2. Linux安装pycharm并添加图标到桌面

    安装: 1.到pycharm官网下载Linux版本的pycharm包. 2.打开中端 cd到下载的文件夹,默认为 ~/Downloads/ 文件夹下 3.执行命令 tar -xvzf pycharm- ...

  3. pkusc2019游记

    Day0 早上 6:55 的高铁,6 点就起了,好困呜呜呜 去的路上跟 memset0 坐一起,突然发现雀魂还没停服,先雀了一局(居然拿了个 1 位还飞了一个人),与此同时 memset0 切了一道毒 ...

  4. 使用overnightjs typescript 注解开发expressjs 应用

    overnightjs 提供了基于注解的expressjs应用开发,包含了比较全的express 开发支持,使用简单,以下是一个简单的试用 项目准备 项目使用pkg 进行了打包处理 初始化 yarn ...

  5. ACM之Java输入输出

    本文转自:ACM之Java输入输出 一.Java之ACM注意点 1. 类名称必须采用public class Main方式命名 2. 在有些OJ系统上,即便是输出的末尾多了一个“ ”,程序可能会输出错 ...

  6. 06-图2 Saving James Bond - Easy Version (25 分)

    This time let us consider the situation in the movie "Live and Let Die" in which James Bon ...

  7. ImportError: No module named 'typing'

    k@ubuntu:~/Desktop/virtualenv$ python3 Python ( , ::) [GCC ] on linux Type "help", "c ...

  8. 「NOIP2016」换教室

    传送门 Description 对于刚上大学的牛牛来说,他面临的第一个问题是如何根据实际情况申请合适的课程. 在可以选择的课程中,有 $ 2n $ 节课程安排在 $ n $ 个时间段上.在第 $ i ...

  9. 牛顿迭代法(c++)

    编写一个用牛顿法解方程x=tanx 的程序,求最接近4.5和7.7的根 #include <iostream> #include <cmath> using namespace ...

  10. Net core学习系列(七)——Net Core中间件

    一.什么是中间件(Middleware)? 中间件是组装到应用程序管道中以处理请求和响应的软件. 每个组件: 选择是否将请求传递给管道中的下一个组件. 可以在调用管道中的下一个组件之前和之后执行工作. ...