【微服务~远程调用】整合RestTemplate、WebClient、Feign

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
云原生网关 MSE Higress,422元/月
注册配置 MSE Nacos/ZooKeeper,118元/月
简介: 【微服务~远程调用】整合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>

编写配置类

image.png

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();
    }
}

编写测试类

image.png

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);  // 将结果转换为指定类型
    }
}

测试

http://localhost:8071/client/echo/123

image.png

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

image.png

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);
}

编写测试类

image.png

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);
    }
}

修改启动类

image.png

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 );
    }
}


相关实践学习
部署高可用架构
本场景主要介绍如何使用云服务器ECS、负载均衡SLB、云数据库RDS和数据传输服务产品来部署多可用区高可用架构。
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
相关文章
|
1月前
|
机器学习/深度学习 负载均衡 Java
【SpringBoot系列】微服务远程调用Open Feign深度学习
【4月更文挑战第9天】微服务远程调度open Feign 框架学习
94 2
|
1月前
|
负载均衡 Java Apache
【微服务系列笔记】Feign
Feign是一个声明式的伪HTTP客户端,它使得HTTP请求变得更简单。使用Feign,只需要创建一个接口并注解。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。 OpenFeign 是SpringCloud在Feign的基础上支持了SpringMVC的注解。
66 8
|
7月前
|
负载均衡 Java Maven
微服务技术系列教程(23) - SpringCloud- 声明式服务调用Feign
微服务技术系列教程(23) - SpringCloud- 声明式服务调用Feign
86 0
|
1月前
|
存储 负载均衡 Java
【Spring底层原理高级进阶】微服务 Spring Cloud 的注册发现机制:Eureka 的架构设计、服务注册与发现的实现原理,深入掌握 Ribbon 和 Feign 的用法 ️
【Spring底层原理高级进阶】微服务 Spring Cloud 的注册发现机制:Eureka 的架构设计、服务注册与发现的实现原理,深入掌握 Ribbon 和 Feign 的用法 ️
|
9月前
|
负载均衡 Java API
解密微服务之Feign
当谈到微服务架构和RESTful API调用时,Feign是一个备受欢迎的工具,它可以简化客户端与服务之间的通信。本文将详细介绍Feign,解释它是什么,为什么它如此重要,以及如何在你的项目中使用它。
|
1月前
|
Java Apache 开发者
【微服务】5、声明式 HTTP 客户端 —— Feign
【微服务】5、声明式 HTTP 客户端 —— Feign
60 0
|
8月前
|
负载均衡 Dubbo 网络协议
微服务RPC框架:Feign和Dubbo
微服务RPC框架:Feign和Dubbo
381 0
|
8月前
|
负载均衡 Java 开发者
微服务组件 Open Feign 远程调用
OpenFeign是一个声明式的Web服务客户端,它是Spring Cloud生态系统中的一个组件,用于简化和优化微服务之间的远程调用。通过使用注解和接口定义的方式,开发者可以轻松地实现对其他微服务的访问。 使用OpenFeign,您只需定义一个接口,并通过注解来配置该接口对应的远程服务的URL、请求方法、请求参数等信息,OpenFeign将自动生成可用于调用远程服务的实现。这样,您就可以像调用本地方法一样调用远程服务,而无需编写繁琐的HTTP请求和解析代码。
129 0
|
8月前
|
Cloud Native 应用服务中间件 Go
深入解析:探索Nginx与Feign交锋的背后故事 - 如何优雅解决微服务通信中的`301 Moved Permanently`之谜!
深入解析:探索Nginx与Feign交锋的背后故事 - 如何优雅解决微服务通信中的`301 Moved Permanently`之谜!
90 0
|
11月前
|
JSON 算法 Java
Spring Cloud & Alibaba 实战 | 第十二篇: 微服务整合Sentinel的流控、熔断降级,赋能拥有降级功能的Feign新技能熔断,实现熔断降级双剑合璧(二))(JMeter模拟测试)
Spring Cloud & Alibaba 实战 | 第十二篇: 微服务整合Sentinel的流控、熔断降级,赋能拥有降级功能的Feign新技能熔断,实现熔断降级双剑合璧(JMeter模拟测试)(二)

热门文章

最新文章