OpenFeign 的请求处理流程

流程

1. 定义 Feign 客户端接口

首先,开发者需要定义一个 Feign 客户端接口,并使用 @FeignClient 注解进行配置。例如:

@FeignClient(name = "aService", url = "http://localhost:8080")
public interface ServiceProviderClient {
    @GetMapping("/data")
    String getData();
}

2. 创建 Feign 客户端实例

当 Spring Boot 应用启动时,Spring Cloud 会扫描带有 @FeignClient 注解的接口,并使用 Feign.Builder 创建 Feign 客户端实例。

3. 解析注解并生成请求元数据

Contract 组件会解析接口中的注解(如 @GetMapping),并生成相应的 HTTP 请求元数据。

4. 编码请求体

如果请求包含请求体(如 POST 请求),Encoder 会将请求体编码为 HTTP 请求体。

5. 执行 HTTP 请求

Client 组件负责执行实际的 HTTP 请求,并将响应返回。

6. 解码响应体

Decoder 将 HTTP 响应体解码为 Java 对象,并返回给调用者。

示例

下面创建一个简单示例调用百度首页

依赖准备

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Cloud OpenFeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2020.0.4</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

1.创建Feign 客户端接口

@FeignClient(name = "bService", url = "http://www.baidu.com")
public interface ServiceProviderClient2 {
    @GetMapping
    String getData();
}

 2.创建调用接口

@RestController
public class ConsumerController {

  
    @Resource
    private ServiceProviderClient2 serviceProviderClient2;
    
    @GetMapping("/consume2")
    public String consumeService2() {
        return serviceProviderClient2.getData();
    }
}

3.创建启动类

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

4.测试

总结

OpenFeign 通过声明式的注解简化了 Web 服务客户端的编写。其核心组件包括 @FeignClient 注解、Feign.BuilderContractEncoderDecoder 和 Client

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值