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集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏