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 {

    @Autowired
    private 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 {

        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;

        @Bean
        public 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 中增加测试方法,完成处理逻辑
    @Autowired
    private FileUploadClient fileUploadClient;

    @Test
    @SneakyThrows
    public 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));
    }
  • 步骤六:运行,观察日志输出

文件上传

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值