Feign的使用(声明式REST客户端)

什么是Feign?

Feign是一个集成了Ribbon的声明式的Web服务客户端。这使得Web服务客户端的写入更加方便 要使用Feign创建一个界面并对其进行注释。它具有可插入注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插拔编码器和解码器。Spring Cloud增加了对Spring MVC注释的支持,并使用Spring Web中默认使用的HttpMessageConverters。Spring Cloud集成Ribbon和Eureka以在使用Feign时提供负载均衡的http客户端。

Feign的使用如下:

一、添加依赖

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>

二、在启动类上加入@EnableFeignClients

@EnableFeignClients
@SpringBootApplication
@EnableEurekaClient
public class FeignApplication {
  public static void main(String[] args) {
    SpringApplication.run(FeignApplication.class, args);
  }
}

 三、新建一个接口(声明式),使用@FeignClient注解

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {

  @GetMapping("/users/{id}")
  User findById(@PathVariable("id") Long id);

}

说明:microservice-provider-user是服务提供者的Application Name。

 四、在需要使用Feign接口的地方引入即可使用

  @Autowired
  private UserFeignClient userFeignClient;

注意:参数是对象的话,即使代码写的是Get方法,feign也会自动变为Post方法请求远程服务的。

举例:

  //服务提供方
  @GetMapping("/saveUser")
  public User saveUser(@RequestBody User user) {
    System.out.println(user.getUsername());
    return user;
  }
  
  //Feign客户端
  @GetMapping("/users/saveUser")
  public User saveUser() {
    User user = new User();
    user.setUsername("river");
    return userFeignClient.saveUser(user);
  }
 
  //Feign声明的接口
  @GetMapping("users/saveUser")
  User saveUser(@Param("user") User user);

 报错:"status":405,"error":"Method Not Allowed","message":"Request method 'POST' not supported"

改正错误: 把服务提供方的请求方法改为Post

  @PostMapping("/saveUser")
  public User saveUser(@RequestBody User user) {
    System.out.println(user.getUsername());
    return user;
  }

关于Feign的详细使用,可以阅读Spring-Cloud的文档:https://www.springcloud.cc/spring-cloud-dalston.html#spring-cloud-feign

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章