Spring Cloud 学习 --- 声明式REST客户端 Fegin

2024-04-02 16:38

本文主要是介绍Spring Cloud 学习 --- 声明式REST客户端 Fegin,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

基于上一文 Eureka服务注册与发现 中的项目,继续完成关于 Fegin 相关的代码编写。

本次学习最终实现效果

fegin

版本信息

https://spring.io/projects/spring-cloud

  • Spring Boot 版本:2.1.11.RELEASE
  • Spring Cloud 版本:Greenwich.SR4

WHAT — 定义

来自 官网 的定义:

Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka, as well as Spring Cloud LoadBalancer to provide a load-balanced http client when using Feign.

Feign是一个声明性web服务客户端。它使编写web服务客户端变得更容易。使用Feign创建一个接口并对其进行注释。它有可插入的注释支持,包括外部注释和JAX-RS注释。Feign还支持可插入的编码器和解码器。Spring Cloud增加了对Spring MVC注释的支持,以及对使用Spring Web中默认使用的httpMessageConverter的支持。Spring Cloud集成了Ribbon和Eureka以及Spring Cloud LoadBalancer,在使用Feign时提供了一个负载平衡的http客户端。

什么是声明式?

声明式调用就像调用本地方法一样调用远程方法,无感知远程HTTP请求。它解决了让开发者调用远程接口就跟调用本地方法一样,无需关注与远程的交互细节,更无需关注分布式环境开发。

WHY — 特点

Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。

使用Feign,只需要创建一个接口并注解,它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解,Feign支持可插拔的编码器和解码器,Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。

Feign 具有如下特性:

  • 可插拔的注解支持,包括Feign注解和JAX-RS注解
  • 支持可插拔的HTTP编码器和解码器
  • 支持Hystrix和它的Fallback
  • 支持Ribbon的负载均衡
  • 支持HTTP请求和响应的压缩Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单。它整合了RibbonHystrix,从而不再需要显式地使用这两个组件。Feign还提供了HTTP请求的模板,通过编写简单的接口和注解,就可以定义好HTTP请求的参数、格式、地址等信息。接下来,Feign会完全代理HTTP的请求,我们只需要像调用方法一样调用它就可以完成服务请求。

简而言之:Feign能干RibbonHystrix的事情,但是要用RibbonHystrix自带的注解必须要引入相应的jar包才可以。

HOW — 使用

入门调用
  • 步骤一:修改 pom 文件,添加 Feign 依赖
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • 步骤二:修改启动类,添加开启 Feign 注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients  //开启Feign客户端
public class EurekaClientConsumerApplication {public static void main(String[] args) {SpringApplication.run(EurekaClientConsumerApplication.class, args);}}
  • 步骤三:编写 Feign 接口,完成远程调用,取代 dao
/*** @Description: 用户模块通过feign调用接口** 定义个feign接口 @FeignClient("服务名") 来确定调哪个服务*/
@FeignClient(name = "eureka-client-provider")
public interface UserFeignClient {@GetMapping("/login")String login();
}
  • 步骤四:修改 controller, 将调用 dao 修改成 feign
@RestController
public class UserController {@Autowiredprivate UserFeignClient userFeignClient;@GetMapping("/userlogin")public String login() {return "8881收到结果:" + userFeignClient.login();}
}

上面使用 fegin 为入门版,后面的几种调用更接近实际开发:多参数调用实体类调用图片上传

多参数调用
  • 步骤一:provider 中增加调用方法,完成处理逻辑
    @PostMapping("/userLoginPostParam")public String postParamLogin(@RequestParam("name") String name, @RequestParam("pwd") String pwd) {String result = "登录失败。";if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(pwd)) {if (name.equals("tyron") && pwd.equals("123456")) {result = "登录成功";}}return result;}
  • 步骤二:consumerservices 增加接口,供 controller 调用
    @PostMapping("/userLoginPostParam")String postParamLogin(@RequestParam("name") String name, @RequestParam("pwd") String pwd);
  • 步骤三:consumercontroller 增加方法,暴露给外部调用
    @PostMapping("/userLoginPostParam")public String postParamLogin(@RequestParam("name") String name, @RequestParam("pwd") String pwd) {return "登录结果:" + userFeignClient.postParamLogin(name, pwd);}
  • 步骤四:postman调用

postman调用

实体类调用
  • 步骤一:引入 common 项目,方便 providerconsumer 项目同时调用

构建 maven 项目即可!链接:

  • 步骤二:common 项目创建实体类 UserModel
@Getter
@Setter
public class UserModel {private String name;private String pwd;private int age;private Date birthday;}
  • 步骤三:providerconsumer 项目同时引入 common 项目
<!--common依赖-->
<dependency><groupId>com.tyron</groupId><artifactId>common</artifactId><version>1.0-SNAPSHOT</version>
</dependency>
  • 步骤四:provider 中增加调用方法,完成处理逻辑
	@PostMapping("/userLoginPostModel")public String postModelLogin(@RequestBody UserModel userModel) {String result = "登录失败。";if (StringUtils.isNotEmpty(userModel.getName()) && StringUtils.isNotEmpty(userModel.getPwd())) {if (userModel.getName().equals("tyron") && userModel.getPwd().equals("654321")) {result = "登录成功";}}return result;}
  • 步骤五:consumerservices 增加接口,供 controller 调用
    @PostMapping("/userLoginPostModel")String userLoginPostModel(@RequestBody UserModel userModel);
  • 步骤六:consumercontroller 增加方法,暴露给外部调用
    @PostMapping("/userLoginPostModel")public String postModelLogin(@RequestBody UserModel userModel) {return "登录结果:" + userFeignClient.userLoginPostModel(userModel);}
  • 步骤七:postman调用

postman调用

文件上传
  • 步骤一:provider 中增加调用方法,完成处理逻辑
@RestController
public class FileUpload {@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {if (file == null) {return "文件不能为空。";}return file.getOriginalFilename() + "的文件上传成功";}
}
  • 步骤二:consumerapplication.yml 修改配置文件
spring:application:name: eureka-client-consumer# 多个接口上的@FeignClient(“相同服务名”)会报错:name has already been defined and overriding is disabled。# 设置 为true ,即 允许 同名main:allow-bean-definition-overriding: true
  • 步骤三:provider 中增加调用方法,完成处理逻辑
@FeignClient(name = "eureka-client-provider", configuration = FileUploadClient.MultipartSupportConfig.class)
public interface FileUploadClient {@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)String handleFileUpload(@RequestPart(value = "file") MultipartFile file);public class MultipartSupportConfig {@Autowiredprivate ObjectFactory<HttpMessageConverters> messageConverters;@Beanpublic Encoder feignFormEncoder() {return new SpringFormEncoder(new SpringEncoder(messageConverters));}}
}
  • 步骤四:consumer 项目引入依赖
<dependency><groupId>io.github.openfeign.form</groupId><artifactId>feign-form</artifactId><version>3.8.0</version>
</dependency>
<dependency><groupId>io.github.openfeign.form</groupId><artifactId>feign-form-spring</artifactId><version>3.8.0</version>
</dependency>
<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version>
</dependency>
  • 步骤五:provider 中增加测试方法,完成处理逻辑
    @Autowiredprivate FileUploadClient fileUploadClient;@Test@SneakyThrowspublic void testHandleFileUpload() {File file = new File("C:\\Users\\Administrator\\Desktop\\111.txt");DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",MediaType.TEXT_PLAIN_VALUE, true, file.getName());try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {IOUtils.copy(input, os);} catch (Exception e) {throw new IllegalArgumentException("Invalid file: " + e, e);}MultipartFile multi = new CommonsMultipartFile(fileItem);log.info(fileUploadClient.handleFileUpload(multi));}
  • 步骤六:运行,观察日志输出

文件上传

参考

  • OpenFeign/feign
  • 官方Feign文件上传
  • tyronczt/Spring-Cloud-Learning 提交记录
  • Spring Cloud中如何优雅的使用Feign调用接口
  • 学习SpringCloud Feign带你从0到1
  • Spring Cloud Feign的文件上传实现

这篇关于Spring Cloud 学习 --- 声明式REST客户端 Fegin的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/870508

相关文章

一文详解SpringBoot中控制器的动态注册与卸载

《一文详解SpringBoot中控制器的动态注册与卸载》在项目开发中,通过动态注册和卸载控制器功能,可以根据业务场景和项目需要实现功能的动态增加、删除,提高系统的灵活性和可扩展性,下面我们就来看看Sp... 目录项目结构1. 创建 Spring Boot 启动类2. 创建一个测试控制器3. 创建动态控制器注

Java操作Word文档的全面指南

《Java操作Word文档的全面指南》在Java开发中,操作Word文档是常见的业务需求,广泛应用于合同生成、报表输出、通知发布、法律文书生成、病历模板填写等场景,本文将全面介绍Java操作Word文... 目录简介段落页头与页脚页码表格图片批注文本框目录图表简介Word编程最重要的类是org.apach

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注