Contents

Feign客户端使用@Requestline

1. 概述

在本教程中,我们将演示如何在Feign客户端中使用 @RequestLine 注解。@RequestLine是一个模板,用于定义用于连接 RESTful Web 服务的 URI 和查询参数。

2. Maven依赖

首先,让我们创建一个Spring Boot Web 项目并将spring-cloud-starter-openfeignfeign-core 依赖项包含到我们的pom.xml文件中。spring-cloud-starter-openfeign在其中包含feign-core依赖项:

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

或者

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-core</artifactId>
    <version>11.8</version>
</dependency>

3. Feign 客户端中的*@RequestLine*

@RequestLine Feign 注解将HTTP 动词、路径和请求参数指定为 Feign 客户端中的参数。路径和请求参数是使用*@Param*注释指定的。

通常在 Spring Boot 应用程序中,我们会使用*@FeignClient*,但如果我们不想使用spring-cloud-starter-openfeign依赖项,我们也可以使用*@RequestLine*。如果我们将*@RequestLine@FeignClient一起使用,则使用该依赖项会给我们一个IllegalStateException*。

@FeignClient注解的String值是用于创建 Spring Cloud LoadBalancer 客户端的任意名称。我们可能会根据需要额外指定 URL 和其他参数。

让我们创建一个使用*@RequestLine*的接口:

public interface EmployeeClient {
    @RequestLine("GET /empployee/{id}?active={isActive}")
    @Headers("Content-Type: application/json")
    Employee getEmployee(@Param long id, @Param boolean isActive);
}

我们还应该提供*@Headers我们定义其余API*所需的标头。

现在,我们将调用由此创建的接口来调用实际的API

EmployeeClient employeeResource = Feign.builder().encoder(new SpringFormEncoder())
  .target(EmployeeClient.class, "http://localhost:8081");
Employee employee = employeeResource.getEmployee(id, true);