1. 概述
在本教程中,我們將演示如何在 Feign 客户端中使用 @RequestLine 註解。 @RequestLine 是定義與 RESTful Web 服務連接的 URI 和查詢參數的模板。
2. Maven 依賴
首先,我們創建一個 Spring Boot Web 項目,並將 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>
或者
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>13.1</version>
</dependency>
3. @RequestLine in 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.
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.
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.
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. 結論
在本文中,我們展示瞭如何以及何時使用 RequestLine 註解在 Feign 客户端。