RequestLine with Feign Client – 带有伪装客户的RequestLine

最后修改: 2022年 5月 24日

1. Overview


In this tutorial, we’ll demonstrate how to use @RequestLine annotation in Feign client. @RequestLine is a template for defining the URI and query parameter for connecting with a RESTful web service.


2. Maven Dependency


To begin, let’s create a Spring Boot web project and include the spring-cloud-starter-openfeign or feign-core dependency to our pom.xml file. The spring-cloud-starter-openfeign includes feign-core dependency within it:

首先,让我们创建一个Spring Boot网络项目,并将spring-cloud-starter-openfeignfeign-core依赖性纳入我们的pom.xml文件。spring-cloud-starter-openfeign包括feign-core的依赖关系。




3. @RequestLine in Feign Client

3.@RequestLineFeign Client中。

The @RequestLine Feign annotation specifies the HTTP verb, path, and request parameters as arguments in the Feign client. The path and request parameters are specified using the @Param annotation.

@RequestLine Feign注解指定了HTTP动词、路径和请求参数作为Feign客户端的参数。路径和请求参数是用@Param注解指定的。

Normally in a Spring Boot application, we’d use @FeignClient, but we can also use @RequestLine if we don’t want to use the spring-cloud-starter-openfeign dependency. Using that dependency will give us an IllegalStateException if we use @RequestLine with @FeignClient.

通常在Spring Boot应用程序中,我们会使用@FeignClient,但如果我们不想使用@RequestLine,我们也可以使用spring-cloud-starter-openfeigndependency。如果我们将@RequestLine@FeignClient一起使用,使用该依赖关系将给我们带来IllegalStateException

The @FeignClient annotation’s String value is an arbitrary name that is used to create a Spring Cloud LoadBalancer client. We may additionally specify a URL and other parameters based on the requirements.

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

Let’s create an interface for using @RequestLine:


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

We should also provide @Headers where we define headers required by the rest API.


Now, we’ll call the interface thus created to call the actual API:


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

4. Conclusion


In this article, we’ve demonstrated how and when @RequestLine annotation is used in Feign Client.


As is the custom, all code samples used in this tutorial are available on GitHub.