feign-core 与spring-boot 整合

1,557 阅读2分钟

1. 介绍

本文主要是介绍feign-core 与spring-boot 整合后的基本使用,及分析是如何整合的;feign-core原理解析可以参见上一篇:feign-core-基本使用

2. 使用案例

2.1 注册中心

本文采用eurake , 源码中有相应的服务,直接运行main方法即可;

2.2 接口提供

本文以单独的jar项目提供,方便服务消费方使用;参见源码

接口如下:

/**
 * 吃饭
 */
@FeignClient(name = "yiyi-feign-provider", path = "/eat")
public interface EatService {
    /**
     * 吃
     */
    @GetMapping("/apple")
    String eatApple();

    /**
     * 吃🍊
     */
    @GetMapping("/orange")
    String eatOrange(@RequestParam("who") String who);
}

2.3 服务提供方

提供一个HTTP服务即可,可以直接使用本文的spring-boot 项目,参见github-源码

2.4 服务消费方

消费方是本文重点,重点介绍下:

pom配置

引入接口、eureka客户端、feign-core

<dependency>
     <groupId>com.husky</groupId>
     <artifactId>yiyi-feign-intf</artifactId>
     <version>0.0.1-SNAPSHOT</version>
 </dependency>

 <!-- =========================== spring-boot start =========================== -->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

 <!-- =========================== spring-boot end =========================== -->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
     <version>${spring-cloud-version}</version>
 </dependency>

属性配置

app.id=yiyi-feign-consumer
spring.application.name=yiyi-feign-consumer
logging.level.org.apache.http=trace
server.port=18084
spring.main.allow-bean-definition-overriding=true
ribbon.eureka.enabled=true
eureka.client.service-url.defaultZone=http://yiyi.cn:8761/eureka/

启动类配置

@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"com.husky.intf"})
@SpringBootApplication
public class HuskyFeignConsumerApplication {

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

}

Controller调用

@RestController
@RequestMapping("/eat")
public class EatController {

    @Autowired
    private EatService eatService;

    /**
     * 吃
     */
    @GetMapping("/apple")
    public String eatApple() {
        return "provider: " + eatService.eatApple();
    }

    @GetMapping("/orange")
    public String eatOrange(String who) {
        return eatService.eatOrange(who);
    }
}

2.5 启动

依次启动 注册中心、服务提供方、服务消费方;

postman访问: localhost:18084/eat/apple

返回结果:provider: 我吃了 苹果 on 18081

3. 整合原理

注: 如果你对feign-core原理不太了解,建议先看一下上篇文章:feign-core-基本使用,本文侧重feign-core 是如何与spring-boot 进行整合的,feign-core原理会一笔带过;

3.1 feign-core 原理回顾

代理对象的生成流程如下:

3.2 预想一下

在了解原理前,先思考🤔以下几个问题?

1)我们要神马?

要一个接口的代理对象

2)spring-boot 整合框架大多都如何起作用呢?

一般都是在启动类上加 @EnableXxx 注解

3.3 庖丁解牛

根据3.2 的预想,我们以启动类上的 @EnableFeignClient 注解为切入口,分析 代理类的加载逻辑;

如下图所示:我们的分析流程如下:

注: 到最后一步:registerFeignClients() ,我们得到可以生成接口代理对象的 FactoryBean ;

那么啥时候生成代理对象呢?

自然是@Autowired 赋值的时候

@Autowired
private EatService eatService;

至此代理类就可以提供服务了

参见

本文源码地址-github

聊聊Fein的实现原理

Spring Cloud 整合 Feign 的原理