How to call a third-party API using feignclient?
To call a third-party API using FeignClient, follow these steps:
- Add the Feign dependency to the pom.xml file.
<dependencies>
...
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
...
</dependencies>
- Activate Feign Clients
@SpringBootApplication
@EnableFeignClients
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- Using the @FeignClient annotation
@FeignClient(name = "third-party-api", url = "http://api.example.com")
public interface ThirdPartyApi {
@GetMapping("/users/{id}")
User getUserById(@PathVariable("id") Long id);
@PostMapping("/users")
User createUser(@RequestBody User user);
// 其他需要调用的接口方法
}
The name attribute represents the name of the FeignClient, while the url attribute represents the URL of the third-party interface.
- Inject the FeignClient interface where third-party API calls are needed and use its methods for invocation.
@RestController
public class YourController {
private final ThirdPartyApi thirdPartyApi;
public YourController(ThirdPartyApi thirdPartyApi) {
this.thirdPartyApi = thirdPartyApi;
}
@GetMapping("/users/{id}")
public User getUser(@PathVariable("id") Long id) {
return thirdPartyApi.getUserById(id);
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return thirdPartyApi.createUser(user);
}
// 其他需要调用第三方接口的方法
}
This allows you to call third-party APIs through FeignClient. FeignClient automatically constructs requests based on the defined interface methods and provides some configurable options such as request timeout, request retry, etc. These configurations can be adjusted according to your needs during actual usage.