当前位置:网站首页>【微服务~远程调用】整合RestTemplate、WebClient、Feign
【微服务~远程调用】整合RestTemplate、WebClient、Feign
2022-07-22 07:13:00 【陶然同学】
这里是【微服务~远程调用】,关注我学习微服务不迷路
如果对你有帮助,给博主一个免费的点赞以示鼓励
欢迎各位点赞评论收藏️
专栏介绍
【微服务~远程调用】 目前主要更新微服务,一起学习一起进步。
本期介绍
本期主要介绍远程调用整合整合RestTemplate、WebClient、Feign
文章目录
整合RestTemplate
对RestTemplate进行增强,支持负载均衡
package com.czxy.nacos.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class RestTemplateConfig {
@LoadBalanced //负载均衡
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
通过服务名
调用服务提供者
package com.czxy.nacos.controller;
import com.czxy.nacos.feign.TestFeign;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
public class TestController {
@Resource
private RestTemplate restTemplate;
@RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
public String echo(@PathVariable String str) {
return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
}
}
整合WebClient
WebClient和RestTemplate
RestTemplate 是 spring 3.0 引入的,底层IO模型是阻塞IO模型 Http客户端。
WebClient 是 spring 5.0 引入的,作为非阻塞式Reactive Http客户端,用于取代RestTemplate。
响应式IO模型
SpringMVC或Struct等框架都是基于Servlet的,其底层IO模型是阻塞IO模型。
Spring社区为了解决SpringMVC的阻塞模型在高并发场景下的性能瓶颈,推出了Spring WebFlux,WebFlux底层实现是久经考验的Netty非阻塞IO通信框架。
其实WebClient处理单个HTTP请求的响应时长并不比RestTemplate更快,但是它处理==并发==的能力更强。 所以响应式非阻塞IO模型的核心意义在于,提高了单位时间内有限资源下的服务请求的并发处理能力,而不是缩短了单个服务请求的响应时长。
总结:WebClient --> Spring WebFlux --> Netty
WebClient入门
添加 webflux 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
编写配置类
package com.czxy.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
@Component
public class WebClientConfig {
@Bean
@LoadBalanced
public WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
}
编写测试类
package com.czxy.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import javax.annotation.Resource;
@RestController
@RequestMapping("/client")
public class TestClientController {
@Resource
private WebClient.Builder webClientBuilder;
@GetMapping("/echo/{str}")
public Mono<String> echo(@PathVariable("str") String str) {
return webClientBuilder.build() // 创建WebClient实例
.get() // 请求方式
.uri("http://service-provider/echo/{1}", str) // 请求url
.retrieve() // 获取响应结果
.bodyToMono(String.class); // 将结果转换为指定类型
}
}
测试
API详解
请求方式
方法 | 描述 | 等效 |
---|---|---|
build().get() | get请求 | build().method(HttpMethod.GET) |
build().post() | post请求 | build().method(HttpMethod.POST) |
build().put() | put请求 | build().method(HttpMethod.PUT) |
build().delete() | delete请求 | build().method(HttpMethod.DELETE) |
响应类型
类型 | 描述 | 方法 |
---|---|---|
Mono | 包含0个或1个元素 | bodyToMono(String.class) |
Flux | 包含1个或多个元素 | .bodyToFlux(String.class) |
整合Feign
概述
RestTemplate和WebClient都是Spring自己封装的工具
Feign 是 Spring Cloud 的成员
Spring Cloud Alibaba 支持对Feign的调用
整合Feign
添加坐标
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
编写feign
package com.czxy.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
// @FeignClient(value = "服务名", path = "controller配置的路径" )
@FeignClient(value = "service-provider")
public interface EchoFeign {
// 与 nacos-provider-2.1>EchoController声明的方法的完全一致
@GetMapping("/echo/{string}")
public String echo(@PathVariable String string);
}
编写测试类
package com.czxy.controller;
import com.czxy.feign.EchoFeign;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/feign")
public class TestFeignController {
@Resource
private EchoFeign echoFeign;
@GetMapping("/echo/{str}")
public String echo(@PathVariable String str) {
return echoFeign.echo(str);
}
}
修改启动类
package com.czxy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient //服务发现
@EnableFeignClients //远程调用
public class TestNacosConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(TestNacosConsumerApplication.class, args );
}
}
边栏推荐
- [harmony OS] [ark UI] [demo] loading animation
- [how to optimize her] teach you how to locate unreasonable SQL? And optimize her~~~
- Li Hongyi machine learning 2020--p20 & 21 RNN
- [HMS core] [Health Kit] [FAQ] collection of data subscription function questions
- MySQL series article 4: execution plan
- mysql查询中能否同时判断多个字段的值
- 指令安排问题
- 1312. Minimum number of inserts to make a string a palindrome string
- MySQL系列文章之四:执行计划
- Implementation of MATLAB mixer
猜你喜欢
132. Split palindrome string II
OSPF special area comprehensive experiment
Android interview question: what is the difference between pendingintent and intent?
Mongodb query statement >, & gt;=、& lt;、& lt;=、=、!=、 In, not in usage introduction
On the dilemma faced by non transferable reputation points NFT SBTS
Win11 Beta 22621.436和22622.436有什么区别?
如何一边看全景一边预约点餐?VR餐饮系统教程来了
Data Lake (18): Flink and iceberg integrate SQL API operations
并发程序的噩梦——数据竞争
MySQL JDBC programming
随机推荐
VR全景在各行各业是如何展示?如何落地应用的?
Map insert element
【数据库】MySQL表的增删改查(基础)
Conference OA project introduction & Conference release
Instruction arrangement problem
【开发者必看】【push kit】推送服务服务典型问题合集1
MySQL series article 4: execution plan
【FPGA教程案例35】通信案例5——基于FPGA的16QAM调制信号产生,通过matlab测试其星座图
[external sorting] merge ideas to complete external sorting
Rendering process of browser pages
2022-07-21: given a string STR and a positive number k, you can divide STR into multiple substrings at will. The purpose is to find that in a certain division scheme, there are as many palindrome subs
奇瑞星途产品规划曝光,2.0t涡轮增压发动机,年底推出
354. Russian Doll envelope problem
Misc advanced
缓动动画、窗口相关数据和操作、BOM操作【DOM(五)】
PostgreSQL database is deployed on Linux server. Ms level is queried locally. Pgadmin installed on windows is used to query super slow for about 20s. Is it a network problem or a database configuratio
STL map
MySQL 增删改查(进阶)
Chery Xingtu's product plan was exposed, and the 2.0T turbocharged engine was launched at the end of the year
Graduation thesis on production line balance optimization [Flexsim simulation]