微服务系列-使用WebFlux的WebClient进行Spring Boot 微服务通信示例
公众号「架构成长指南」,专注于生产实践、云原生、分布式系统、大数据技术分享。
概述
在之前的教程中,我们看到了使用 RestTemplate 的 Spring Boot 微服务通信示例。
从 5.0 开始,RestTemplate处于维护模式,很快就会被弃用。因此 Spring 团队建议使用org.springframework.web.reactive.client.WebClient ,它支持同步、异步和流场景。
在本教程中,我们将学习如何使用WebClient在多个微服务之间进行 REST API 调用(同步通信)。
WebClient是一个非阻塞的响应式客户端,用于执行 HTTP 请求,通过底层 HTTP 客户端库(例如 Reactor Netty)来实现。
要在 Spring boot 项目中使用WebClient,我们必须将Spring WebFlux依赖项添加到类路径中。
我们需要做什么
下面将创建两个微服务,例如 部门服务 和 用户服务,并且我们将使用WebClient从 用户服务 到 部门服务 进行 REST API 调用 ,以获取特定的用户部门数据。

基础配置
我们在上一篇文章中创建了两个微服务: 使用 RestTemplate 的 Spring Boot 微服务通信示例。
第1步:添加Spring WebFlux依赖
打开user-service项目的pom.xml文件并添加以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-resolver-dns-native-macos</artifactId>
<classifier>osx-aarch_64</classifier>
</dependency>
可以看到上面还添加了netty-resolver-dns-native-macos的pom,原因是如果不添加此报会抛出相关异常,问题详情
第2步:将WebClient配置为Spring Bean
package io.wz.userservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.client.WebClient;
@SpringBootApplication
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
@Bean
public WebClient webClient(){
return WebClient.builder().build();
}
}
第三步:注入并使用WebClient调用REST API
让我们注入WebClient并使用它来进行 REST API 调用:
DepartmentDto departmentDto = webClient.get()
.uri("http://localhost:8080/api/departments/" + user.getDepartmentId())
.retrieve()
.bodyToMono(DepartmentDto.class)
.block();
下面是UserServiceImpl类的完整代码, 供大家参考:
package io.wz.userservice.service.impl;
import io.wz.userservice.dto.DepartmentDto;
import io.wz.userservice.dto.ResponseDto;
import io.wz.userservice.dto.UserDto;
import io.wz.userservice.entity.User;
import io.wz.userservice.repository.UserRepository;
import io.wz.userservice.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
private WebClient webClient;
@Override
public User saveUser(User user) {
return userRepository.save(user);
}
@Override
public ResponseDto getUser(Long userId) {
ResponseDto responseDto = new ResponseDto();
User user = userRepository.findById(userId).get();
UserDto userDto = mapToUser(user);
DepartmentDto departmentDto = webClient.get()
.uri("http://localhost:8080/api/departments/" + user.getDepartmentId())
.retrieve()
.bodyToMono(DepartmentDto.class)
.block();
responseDto.setUser(userDto);
responseDto.setDepartment(departmentDto);
return responseDto;
}
private UserDto mapToUser(User user){
UserDto userDto = new UserDto();
userDto.setId(user.getId());
userDto.setFirstName(user.getFirstName());
userDto.setLastName(user.getLastName());
userDto.setEmail(user.getEmail());
return userDto;
}
}
下面运行两个微服务并进行测试。
测试:启动两个微服务
首先启动部门服务项目,然后启动用户服务项目,一旦两个项目都启动并在不同的端口上运行。接下来,我们调用Get User REST API来测试user-service REST API 对Department-service 的调用。
获取用户 REST API:

请注意,响应结果包含了用户的部门。这说明我们已成功使用WebClient从用户服务到部门服务进行 REST API 调用。
结论
在本教程中,我们学习了 如何使用WebClient 在多个微服务之间进行 REST API 调用(同步通信)。
微服务系列-使用WebFlux的WebClient进行Spring Boot 微服务通信示例的更多相关文章
- 【原创】Docker容器及Spring Boot微服务应用
Docker容器及Spring Boot微服务应用 1 什么是Docker 1.1 Docker的出现 问题一:项目实施环境复杂问题 传统项目实施过程中经常会出现“程序在我这跑得好好的,在你那怎么就不 ...
- 【spring boot】spring cloud下spring boot微服务启动没有报错,但是访问访问不到
spring cloud下spring boot微服务启动没有报错,但是访问访问不到 解决方法: 可能是端口被占用了,但是依旧启用成功了. 更改一下项目启用的端口号,再重新启动查看是否可以正常访问.
- Spring Boot 微服务应用集成Prometheus + Grafana 实现监控告警
Spring Boot 微服务应用集成Prometheus + Grafana 实现监控告警 一.添加依赖 1.1 Actuator 的 /prometheus端点 二.Prometheus 配置 部 ...
- 3行代码快速实现Spring Boot Oauth2服务
这里的3行代码并不是指真的只需要写3行代码,而是基于我已经写好的一个Spring Boot Oauth2服务.仅仅需要修改3行数据库配置信息,即可得到一个Spring Boot Oauth2服务. 项 ...
- Springboot 系列(十七)迅速使用 Spring Boot Admin 监控你的 Spring Boot 程序,支持异常邮件通知
1. Spring Boot Admin 是什么 Spring Boot Admin 是由 codecentric 组织开发的开源项目,使用 Spring Boot Admin 可以管理和监控你的 S ...
- Spring Cloud第十三篇 | Spring Boot Admin服务监控
本文是Spring Cloud专栏的第十三篇文章,了解前十二篇文章内容有助于更好的理解本文: Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Clo ...
- 53. spring boot系列合集【从零开始学Spring Boot】
前40章节的spring boot系列已经打包成PDF在csdn进行发布了,如果有需要的可以进行下载. 下载地址:http://download.csdn.net/detail/linxinglian ...
- Spring Boot干货系列:(十二)Spring Boot使用单元测试(转)
前言这次来介绍下Spring Boot中对单元测试的整合使用,本篇会通过以下4点来介绍,基本满足日常需求 Service层单元测试 Controller层单元测试 新断言assertThat使用 单元 ...
- Spring Boot微服务架构入门
概述 还记得在10年毕业实习的时候,当时后台三大框架为主流的后台开发框架成软件行业的标杆,当时对于软件的认识也就是照猫画虎,对于为什么会有这么样的写法,以及这种框架的优势或劣势,是不清楚的,Sprin ...
- Spring Boot微服务如何集成fescar解决分布式事务问题?
什么是fescar? 关于fescar的详细介绍,请参阅fescar wiki. 传统的2PC提交协议,会持有一个全局性的锁,所有局部事务预提交成功后一起提交,或有一个局部事务预提交失败后一起回滚,最 ...
随机推荐
- TypeScript: Object is of type 'unknown'.
错误代码展示 解决方案 将e声明为any类型,如下所示: // 修改蛇的X和Y值 try { this.snake.X = X; this.snake.Y = Y; }catch(e:any){ // ...
- python教程 入门学习笔记 第1天 初识python python语言环境安装 python编写器
初识python 一.python语言简介: 1.起源:1989年由荷兰的前谷歌程序员吉多.范罗苏姆(龟叔)创造,python的命名来源于英国电视喜剧Monty Python's Flying Cir ...
- chrome浏览器插件react devtools、redux devtools,无需安装、解压即可用
react devtools用于调试react代码,可以查看到props.state的值,以及定义的hooks,而redux devtools可以追踪到action的派发.store的变化,两个都是r ...
- composer 的使用和常用命令大全
composer 常用命令 1.composer初始化 init 如何手动创建 composer.json 文件.实际上还有一个 init 命令可以更容易的做到这一点. 查看当前版本composer ...
- UI自动化执行过程中,隐藏浏览器页面
在执行UI自动化的过程中,浏览器总是会弹出,如果自动化环境是在个人办公笔记本,在工作过程中会影响正常办公.故需要将UI自动化执行时的浏览器隐藏. 代码实现如下: from selenium impor ...
- form 表单恢复初始数据
1 表单数据的保存和恢复方法 1.1 前端数据保存方法 在前端,我们可以使用两种方法来保存表单数据:LocalStorage 和 Cookie. 使用 LocalStorage 保存数据:LocalS ...
- Unity 编辑器资源导入处理函数 OnPreprocessTexture:深入解析与实用案例
Unity 编辑器资源导入处理函数 OnPreprocessTexture 用法 点击封面跳转下载页面 简介 在Unity中,我们可以使用编辑器资源导入处理函数(OnPreprocessTexture ...
- 论文解读(CTDA)《Contrastive transformer based domain adaptation for multi-source cross-domain sentiment classification》
Note:[ wechat:Y466551 | 可加勿骚扰,付费咨询 ] 论文信息 论文标题:Contrastive transformer based domain adaptation for m ...
- 使用 SQL 的方式查询消息队列数据以及踩坑指南
背景 为了让业务团队可以更好的跟踪自己消息的生产和消费状态,需要一个类似于表格视图的消息列表,用户可以直观的看到发送的消息:同时点击详情后也能查到消息的整个轨迹. 消息列表 点击详情后查看轨迹 原理介 ...
- QA|20211013|SecureCRT:如图,有很多^,中文显示有问题,乱码,如何解决
Q1:如图,有很多^,中文显示有问题,乱码,如何解决 Q2:securecrt的vi展示有问题:少很多字.有很多^M和^,光标无法移动到最右侧 A: 首先检查当前编码格式: 1 echo $LANG ...