Spring Cloud 学习 --- 声明式REST客户端 Fegin
in with 0 comment

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

in with 0 comment

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

本次学习最终实现效果

fegin

版本信息

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

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能干RibbonHystrix的事情,但是要用RibbonHystrix自带的注解必须要引入相应的jar包才可以。

HOW --- 使用

入门调用

<dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients  //开启Feign客户端
public class EurekaClientConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaClientConsumerApplication.class, args);
    }

}
/**
 * @Description: 用户模块通过feign调用接口
 *
 * 定义个feign接口 @FeignClient("服务名") 来确定调哪个服务
 */
@FeignClient(name = "eureka-client-provider")
public interface UserFeignClient {

    @GetMapping("/login")
    String login();
}
@RestController
public class UserController {

    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/userlogin")
    public String login() {
        return "8881收到结果:" + userFeignClient.login();
    }
}

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

多参数调用

    @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;
    }
    @PostMapping("/userLoginPostParam")
    String postParamLogin(@RequestParam("name") String name, @RequestParam("pwd") String pwd);
    @PostMapping("/userLoginPostParam")
    public String postParamLogin(@RequestParam("name") String name, @RequestParam("pwd") String pwd) {
        return "登录结果:" + userFeignClient.postParamLogin(name, pwd);
    }

postman调用

实体类调用

构建 maven 项目即可!链接:

@Getter
@Setter
public class UserModel {

    private String name;
    private String pwd;
    private int age;
    private Date birthday;

}
<!--common依赖-->
<dependency>
    <groupId>com.tyron</groupId>
    <artifactId>common</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
	@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;
    }
    @PostMapping("/userLoginPostModel")
    String userLoginPostModel(@RequestBody UserModel userModel);
    @PostMapping("/userLoginPostModel")
    public String postModelLogin(@RequestBody UserModel userModel) {
        return "登录结果:" + userFeignClient.userLoginPostModel(userModel);
    }

postman调用

文件上传

@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() + "的文件上传成功";
    }
}
spring:
  application:
    name: eureka-client-consumer
    # 多个接口上的@FeignClient(“相同服务名”)会报错:name has already been defined and overriding is disabled。
  # 设置 为true ,即 允许 同名
  main:
    allow-bean-definition-overriding: true
@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));
        }
    }
}
<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>
    @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));
    }

文件上传

参考