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实现RSA+AES自动接口解密的实战指南

《SpringBoot实现RSA+AES自动接口解密的实战指南》在当今数据泄露频发的网络环境中,接口安全已成为开发者不可忽视的核心议题,RSA+AES混合加密方案因其安全性高、性能优越而被广泛采用,本... 目录一、项目依赖与环境准备1.1 Maven依赖配置1.2 密钥生成与配置二、加密工具类实现2.1

在Java中实现线程之间的数据共享的几种方式总结

《在Java中实现线程之间的数据共享的几种方式总结》在Java中实现线程间数据共享是并发编程的核心需求,但需要谨慎处理同步问题以避免竞态条件,本文通过代码示例给大家介绍了几种主要实现方式及其最佳实践,... 目录1. 共享变量与同步机制2. 轻量级通信机制3. 线程安全容器4. 线程局部变量(ThreadL

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.