Spring Cloud Feign

208 阅读2分钟

Spring Cloud Feign是一个声明式的WebService客户端,使得编写WebService客户端变得更简单。它的一个主要优点是它集成了Ribbon和Hystrix,可以在负载均衡和断路器的帮助下轻松调用REST API。

  1. 介绍

    Feign是一个声明式的Web Service客户端,其目的就是让Web Service调用更简单。它通过注解和面向接口的编程风格,让开发者不再关心底层的HTTP请求细节和复杂的错误处理。

  2. 案例使用(java代码)

    首先,你需要在pom.xml中添加Feign的依赖:

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

    然后在Spring Boot的主类中通过@EnableFeignClients注解开启Feign功能:

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

    接着,你可以创建一个接口并用Feign的注解来配置所需要调用的Web Service信息:

    @FeignClient("store-service")
    public interface StoreClient {
        @RequestMapping(method = RequestMethod.GET, value = "/stores")
        List<Store> getStores();
    }
    

    在上述代码中,@FeignClient("store-service")注解标明这是一个Feign客户端,"store-service"是我们想要请求的服务的名称。@RequestMapping注解定义了Service的endpoint。在接口方法中,我们可以定义我们需要消费的服务的方法。

  3. 原理

    Feign在运行时生成了实现了我们定义的接口的代理对象,通过代理技术,将我们定义的接口方法映射为HTTP请求,这个过程是隐藏在背后的,用户无需关心。Feign还整合了Ribbon和Hystrix,为我们提供了负载均衡和断路器,极大地简化了系统间的通信。

    Feign的工作流程主要包括以下几个步骤:

    • 首先,通过@EnableFeignClients注解开启Feign的功能。
    • 然后,程序启动后,Feign会扫描标有@FeignClient注解的接口,生成代理,并注册到Spring容器中。
    • 当接口的方法被调用,通过JDK的代理,Feign会拦截调用,并通过Feign的工具类,将方法调用转换成HTTP请求,发送给服务提供者。
    • 服务提供者处理请求,返回结果,Feign在收到响应后,将响应反序列化成我们预期的类型,返回给消费者。