FeignClientを使用して、サードパーティのAPIを呼び出す方法は?
第三者のAPIを呼び出すためにFeignClientを使用するには、以下の手順に従う必要があります:
- pom.xmlファイルにFeign依存関係を追加してください。
<dependencies>
...
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
...
</dependencies>
- @EnableFeignClientsを有効にします。
@SpringBootApplication
@EnableFeignClients
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- @FeignClientを使って
@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);
// 其他需要调用的接口方法
}
name属性はFeignClientの名前であり、url属性は第三者APIのURLである。
- 第三者インターフェースを呼び出す必要がある場合、FeignClientインターフェースをインジェクトして、そのメソッドを使用して呼び出します。
@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);
}
// 其他需要调用第三方接口的方法
}
FeignClientを使用して、サードパーティーのAPIを呼び出すことができます。定義したインタフェースメソッドに基づいて、FeignClientは自動的にリクエストを構築し、リクエストのタイムアウト時間やリトライなどの設定オプションを提供しています。実際の使用時には、必要に応じて設定できます。