--- title: Spring WebFlux 勉強会 tags: spring robots: noindex, noarchive --- <style> .center { text-align: center; } </style> ### Spring WebFlux - ノンブロッキング I/O - Netty、Servlet 3.1+、Undertow - Mono、Flux - 未来の結果を表す - 非同期で実行される - Reactive Stream の実装 --- ### WebFlux による Reactive プログラミング {%speakerdeck shintanimoto/introduction-to-reactive-programming-using-spring-webflux %} --- ### プログラミングスタイル - 従来のプログラミングスタイルとは異なる - 処理の実行と宣言を分ける - 処理の宣言は関数渡し(コールバック) - map、flatMap、onError、etc... - 処理の実行はフレームワークの裏側に隠されている - 宣言的だと言われてもよくわからん - 遅延評価という話をしたほうが良さそう - コールバックでもいいけど --- ### Reactive Stream - Publisher: Emits a sequence of events to subscribers. - Subscriber: Receives and processes events emitted by a Publisher. - Subscription: Defines a one-to-one relationship between a Publisher and a Subscriber. - Processor: Represents a processing stage consisting of both a Subscriber and a Publisher and obeys the contracts of both. - java のインタフェースを参照 --- ### Mono / Flux - 未来の結果を表す Future に似ている - Future よりパワフル(back-pressure) - どちらも Subscrier - [r2dbc](http://backpaper0.github.io/ghosts/r2dbc/#1) - single、subscribe、etc... - Mono / Flux のインスタンスを作るだけでは処理は走らない(はず) --- ### Mono / Flux - cache - checkpoint - compose - log - subscribe とか single で実行? - Subscription を生成 - subscribeOn に scheduler を指定できる - callable とかを呼び出して Mono に包んで返す - ブロッキングするかどうかは呼び出し側次第 --- ### イベントループ - スレッドプールのようなもの - バックプレッシャー - ストリーム処理ではデータ量を事前に知ることはできない - subscriber の処理量を超えたメッセージを送信しない - subscriver のキューが溢れてメッセージを取りこぼすようなことがない - 処理できない場合は捨てるか、エラーか、リトライ --- ### 向いてること - 非同期でぽんぽんデータを取ってくる - マイクロサービス - 並列に実行できる処理 - アクセスが多いサービス - I/O 待ちが多い場合 - CPU の遊び時間を他の処理に使う --- ### 向いてないこと - ブロッキングで良い処理 - flatMap とか map がいちいち入るのがつらい - メモリを大量に食う処理の並列化 - DB の write がボトルネックになるケース --- ### Scheduler - 実行コンテキストを分けることができる - 並列度 - エラーハンドリング - Controller と DB で並列度を分ける - DB ブロッキングするのでコンテキストを分けたい - HubSpot や外部連携部分は同時呼び出し制限があるので抑える - subscribeOn - `Schedulers.elastic` --- ### Coroutine で読みやすくなる(Kotlin) - ES6 の async/await みたいなやつ - 従来の同期処理のようにかける - 同期処理 - 前の処理結果に依存する - flatMap は文脈依存という表現をよく使う - flatMap は functional 手続き型プログラミングのためにある - map は構造をtamotu --- ### 結果整合性 https://medium.com/@suchakjani/a-case-for-non-blocking-jdbc-part-one-caeadc80fb7c --- ### 参考資料 - [うらがみさんの資料](https://backpaper0.github.io/ghosts/reactive/#1) - [elm の作者の名言](https://hackernoon.com/functional-computational-thinking-what-is-a-monad-2adea91154e) - ”Monad is callback” - [公式リファレンス](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html) - https://www.javaworld.com/article/3288219/mastering-spring-framework-5-part-2-spring-webflux.html - https://kazuhira-r.hatenablog.com/entry/20180811/1533997040 ### 参考資料 - [spring-fu](https://github.com/spring-projects/spring-fu/blob/master/README.adoc)