フェイントはどのようにロードバランシングを実現しますか?
Feignは、宣言型のWebサービスクライアントであり、負荷分散器(たとえばRibbon)と組み合わせて、負荷分散を実現することができます。
Feignを使用して負荷分散を実現するには、次の手順に従う必要があります。
- FeignとRibbonの依存関係を追加してください。以下の依存関係をプロジェクトのpom.xmlファイルに追加してください。
<dependencies>
<!-- 添加Feign依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 添加Ribbon依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
</dependencies>
- @EnableFeignClientsを有効にする
@SpringBootApplication
@EnableFeignClients(basePackages = "com.example.feignclient")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- @FeignClient
@FeignClient(name = "example-service", url = "http://example-service")
public interface ExampleServiceClient {
@GetMapping("/api/example")
String getExample();
}
- Feignクライアントを使用してサービスを呼び出します。Feignクライアントインターフェイスをコードに注入し、そのメソッドを呼び出すことでサービスの呼び出しを実現します。FeignはRibbonと自動的に連携して、負荷分散を実現します。例:
@RestController
public class ExampleController {
private final ExampleServiceClient exampleServiceClient;
public ExampleController(ExampleServiceClient exampleServiceClient) {
this.exampleServiceClient = exampleServiceClient;
}
@GetMapping("/example")
public String getExample() {
return exampleServiceClient.getExample();
}
}
上記の手順を踏むことで、FeignとRibbonを使用して負荷分散を実現することができます。Feignは@FeignClientアノテーションで指定されたサービス名に基づいて、サービス登録センターから利用可能なインスタンスリストを取得し、Ribbonを使用して負荷分散を行い、リクエストを異なるインスタンスに配信します。