Hystrixの基本概念
Hystrixは分散システムにおける遅延や障害を管理するためのライブラリです。リモートサービスや外部ライブラリへのアクセスを隔離し、連鎖的な障害(サービス雪崩)を防止します。
断路メカニズムの動作原理
正常時にはクライアントリクエストがサービスAPIを直接呼び出しますが、サービス障害発生時にはフォールバック処理が実行されます。サービスが過負荷状態の場合、エラーを直接返す代わりに制御された応答を返します。この動作は以下の二つの主要機能で実現されます:
- スレッド分離によるリソース隔離
- サービス断路と機能低下(デグレード)処理
機能低下の実装戦略
機能低下処理はクライアント側で実装され、コアサービスを優先的に維持します。リクエストタイムアウトやスレッドプール枯渇時、事前定義されたフォールバックメソッドが実行されます。
実装手順
依存関係の追加
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
アノテーションの適用
@SpringCloudApplication
public class ServiceEntryPoint {
@Bean
@LoadBalanced
public RestTemplate serviceClient() {
return new RestTemplate();
}
}
コントローラでの設定
@RestController
@RequestMapping("/api")
@DefaultProperties(defaultFallback = "standardFallback")
public class ServiceController {
@Autowired
private RestTemplate serviceClient;
@GetMapping("/resource/{identifier}")
@HystrixCommand
public String fetchResource(@PathVariable Long identifier) {
String endpoint = "http://resource-service/resource/" + identifier;
return serviceClient.getForObject(endpoint, String.class);
}
private String standardFallback() {
return "システム負荷が高い状態です。";
}
}
グローバルタイムアウト設定
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
個別メソッドのタイムアウト設定
@HystrixCommand(commandProperties = {
@HystrixProperty(
name = "execution.isolation.thread.timeoutInMilliseconds",
value = "2000"
)
})