【Spring Cloud】声明式Feign客户端调用工具

末蓝、 2022-03-19 06:58 311阅读 0赞

【学习背景】

通过前面的总结学习,我们可以回想下,是通过什么方式做到服务间的调用的?答案是:Ribbon+RestTemplate,且通过@LoadBalanced注解实现了客户端的负载均衡。本篇博客将介绍另一种调用方式,Feign。Feign也使用了ribbon,只要使用@FeignClient时,ribbon就会自动使用。

【学习内容】

1. Feign框架介绍

Feign 是一个声明web服务客户端,这便得编写web服务客户端更容易,使用Feign 创建一个接口并对它进行注解,它具有可插拔的注解支持包括Feign注解与JAX-RS注解,Feign还支持可插拔的编码器与解码器,Spring Cloud 增加了对 Spring MVC的注解,Spring Web 默认使用了HttpMessageConverters, Spring Cloud 集成 Ribbon 和 Eureka 提供的负载均衡的HTTP客户端 Feign.

2. Feign集成demo

  • 添加Feign maven依赖,基于spring boot 2.0版本的依赖如下:

    1. <dependency>
    2. <groupId>org.springframework.cloud</groupId>
    3. <artifactId>spring-cloud-starter-openfeign</artifactId>
    4. </dependency>
  • 在服务提供者项目中,声明Feign客户端调用接口,调用服务提供者的相关接口:

    // 声明调用的服务名称
    @FeignClient(name = “eureka-service-provider”)
    public interface InvokerApiFeign {

    1. @RequestMapping("/user/{userId}")
    2. public String getServiceProvider(@PathVariable(value = "userId") Integer userId);

    }

此处需要注意的是参数传递需要添加@PathVaiable注解,用value=””标明对应的参数,否则会抛出IllegalStateException异常。

  • 服务消费者中提供对应的接口

    @RestController
    public class FeignController {

    1. @Autowired
    2. private InvokerApiFeign invokerApiFeign;
    3. @RequestMapping("/user/{userId}")
    4. public String getServiceProvider(@PathVariable Integer userId){
    5. return invokerApiFeign.getServiceProvider(userId);
    6. }
  1. }
  • 在Application启动类上添加@@EnableFeignClients注解

    SpringBootApplication
    @EnableEurekaClient
    @EnableFeignClients
    public class EurekaServiceInvokerApplication {

    1. public static void main(String[] args) {
    2. SpringApplication.run(EurekaServiceInvokerApplication.class, args);
    3. }

    }

【学习demo】

对应服务消费者项目更新代码github地址:

https://github.com/huzhiting/spring-cloud/tree/master/eureka-service-invoker

【学习总结】

其实通过Feign封装了HTTP调用服务方法,使得客户端像调用本地方法那样直接调用方法,类似Dubbo中暴露远程服务的方式,区别在于Dubbo是基于私有二进制协议,而Feign本质上还是个HTTP客户端。

发表评论

表情:
评论列表 (有 0 条评论,311人围观)

还没有评论,来说两句吧...

相关阅读