1. Overview
1.概述
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.
在本教程中,我们将演示如何在Feign客户端中使用@RequestLine注释。@RequestLine是一个模板,用于定义URI和查询参数,以便与RESTful网络服务连接。
2. Maven Dependency
2.Maven的依赖性
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-openfeign或feign-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>
Or
或
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>11.8</version>
</dependency>
3. @RequestLine in Feign Client
3.@RequestLine在Feign 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:
让我们为使用@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.
我们还应该提供@Headers,在这里我们定义其余API所需的头文件。
Now, we’ll call the interface thus created to call the actual API:
现在,我们将调用这样创建的接口来调用实际的API。
EmployeeClient employeeResource = Feign.builder().encoder(new SpringFormEncoder())
.target(EmployeeClient.class, "http://localhost:8081");
Employee employee = employeeResource.getEmployee(id, true);
4. Conclusion
4.结论
In this article, we’ve demonstrated how and when @RequestLine annotation is used in Feign Client.
在这篇文章中,我们展示了@RequestLine注解在Feign客户端中的使用方法和时间。
As is the custom, all code samples used in this tutorial are available on GitHub.