イベント
SpringApplication は、Spring Boot と同じく、起動の各段階でイベントを発行します。また、アプリケーションの可用性、つまり生きているかどうかと、トラフィックを受け付けるかどうかを保持します。
使う理由
コードによっては、正確なタイミングで動く必要があります。プロパティが分かった後で、どの Bean も存在する前。あるいはアプリケーションがリクエストを処理できるようになった時点。イベントはこうしたタイミングに名前を与えるため、コードは起動の書き方に依存しません。可用性は、Kubernetes のようなオーケストレーターが尋ねる 2 つの問い、このインスタンスを再起動すべきか、今リクエストを送ってよいか、に答えます。
例
// 起動を遅らせずに、アプリケーションが立ち上がったらキャッシュを埋める。
@Component()
class Warmup {
Warmup(this.cache);
final Cache cache;
@EventListener()
void onReady(ApplicationReadyEvent event) => cache.fill();
}
// どの Bean も存在する前: これを受け取れるのはアプリケーションのリスナーだけ。
@SpringBootApplication()
void main(List<String> args) => (springApplication
..addListener<ApplicationEnvironmentPreparedEvent>(
(event) => print('Profiles: ${event.environment.activeProfiles}'),
))
.run(args);
イベントの順序
| イベント | タイミング | 持つもの |
|---|---|---|
ApplicationStartingEvent |
実行が始まった。まだ何も読まれていない | args |
ApplicationEnvironmentPreparedEvent |
プロパティとプロファイルが分かった。コンテキストはまだない | environment |
ApplicationContextInitializedEvent |
コンテキストが存在し、イニシャライザーが実行された。Bean 定義は読み込まれていない | applicationContext |
ApplicationPreparedEvent |
Bean 定義が読み込まれた。Bean は生成されていない | applicationContext |
ContextRefreshedEvent |
すべてのシングルトンが生成された (コンテキスト自身のイベント) | |
ApplicationStartedEvent |
コンテキストが開始された。次はランナー | applicationContext、timeTaken |
LivenessState.correct の AvailabilityChangeEvent |
ApplicationStartedEvent の直後 |
state |
ApplicationReadyEvent |
ランナーが終わった | applicationContext、timeTaken |
ReadinessState.acceptingTraffic の AvailabilityChangeEvent |
ApplicationReadyEvent の直後 |
state |
ApplicationFailedEvent |
起動またはランナーが失敗したとき、残りの代わりに。失敗レポートの前 | applicationContext (null の場合あり)、exception |
どれも SpringApplicationEvent を継承しており、args を持ちます。
誰が何を受け取るか
ApplicationPreparedEventまでのイベントは、どの Bean も存在する前に起こるため、@EventListenerメソッドがそれらを受け取ることはありません。受け取れるのは、アプリケーションに登録したリスナーだけです:springApplication.addListener<E>(...)、addListeners([...])、SpringApplication(listeners: [...])。ApplicationPreparedEvent以降、それらのリスナーはコンテキストのリスナーにもなるため、コンテキストのイベント (たとえばContextClosedEvent) も受け取ります。ApplicationStartedEvent、ApplicationReadyEvent、可用性のイベント、そして失敗したランナーのApplicationFailedEventはコンテキストを通るため、@EventListenerメソッドとApplicationListenerの Bean がそれらを受け取ります。
ほとんどのアプリケーションに必要なのは、Bean の中の ApplicationReadyEvent だけです。
// アプリケーションのリスナー。他のリスナーとの間での順序付き。
springApplication
..addListener<ApplicationStartingEvent>((event) => print('starting'), order: 0)
..addListeners([
ApplicationListenerAdapter.of<ApplicationFailedEvent>(
(event) => alerts.send('Start failed: ${event.exception}'),
),
]);
可用性
| 状態 | 値 | SpringApplication が設定するもの |
|---|---|---|
LivenessState |
correct、broken |
ApplicationStartedEvent の後に correct |
ReadinessState |
acceptingTraffic、refusingTraffic |
ApplicationReadyEvent の後に acceptingTraffic |
broken なアプリケーションは自力で回復できないため、再起動すべきです。トラフィックを拒否しているアプリケーションは、しばらくリクエストを受け取らないだけです。
applicationAvailability Bean (ApplicationAvailability) は、種類ごとに最後の状態を保持します。
| メンバー | 意味 |
|---|---|
livenessState |
最後の LivenessState。最初の状態の前は broken |
readinessState |
最後の ReadinessState。最初の状態の前は refusingTraffic |
getState<S>(defaultState) |
型 S の最後の状態、または defaultState |
getLastChangeEvent<S>() |
型 S の最後のイベント、または null |
状態はイベントを発行して変更します。
// キャッシュの再構築中は、別の場所にリクエストを送るようロードバランサーに伝える。
@Component()
class CacheRebuild {
CacheRebuild(this.events, this.cache);
final ApplicationEventPublisher events;
final Cache cache;
Future<void> rebuild() async {
AvailabilityChangeEvent.publish(events, ReadinessState.refusingTraffic);
await cache.rebuild();
AvailabilityChangeEvent.publish(events, ReadinessState.acceptingTraffic);
}
}
// 現在の状態はどこでも読める。
if (availability.readinessState == ReadinessState.acceptingTraffic) { ... }
Actuator の liveness と readiness のヘルスグループは、これらの状態から応答します (spring_boot_actuator を参照)。この Bean は ApplicationAvailabilityAutoConfiguration から来ます。独自の ApplicationAvailability Bean はそれを置き換えます。
Spring (Java) との対応
同じイベントが同じ順序で発行され、可用性の型も同じです (LivenessState.CORRECT、ReadinessState.ACCEPTING_TRAFFIC)。早期のイベントのリスナーは、META-INF/spring.factories ではなく、アプリケーションの addListener で追加します。