Spring Web MVC vs WebFlux
Spring မှာ WebFlux မတိုင်ခင်က Srping Web MVC ကိုသုံးတယ်။ WebMVC နဲ့ WebFlux နဲ့ဘာကွာလဲမေးရင် synchronous နဲ့ asynchronous ကွာတယ်ပြောရမယ်။
Synchronous model မှာ HTTP request တခုဖို့ (client request )တခုဖို့ကို process လုပ်ဖို့ Thread တခုသုံးတယ်။
Thread သုံးတော့ဘာဖြစ်လဲဆိုတော့ Thread အတွက် memory manage လုပ်ရတယ်။
Thread switch(context switch )ဖို့ အတွက် CPU ပေးရတယ်။ တကယ်တမ်း Thread 200 ဆိုပါစို့ 200 လုံး တပြိုင်တည်းမ run နိုင်ဘူး။
CPU core ရှိသလောက်သာ run နိုင်တာ။ အဲ့တော့ Thread 1 run ပြီး 2 run ဖို့အတွက်ဆို CPU register တွေထဲက data တွေကို (register value)တွေကို thread အတွက်ထားတဲ့ memory မှာသိမ်းရတယ်။
Context switch ဆိုတာ ခုနက thread ၁ ခုနဲံတခု CPU ကိုနေရာပြောင်းတဲ့အခါ ခုနကသိမ်းထားတဲ့ state တွေကို အတင်အချလုပ်ရတာကိုပြောတာ။
နောက် Java Thread တွေက native thread တွေကိုသုံးတာ ဆိုချင်တာ OS ကပေးထားတဲ့ thread တွေ။ အဲ့ကောင်တွေကလဲ အကန့်အသတ်ရှိတယ်။
နောက်ပိုင်း Java version တွေမှာ ဒါကို handle လုပ်ဖို့ green thread ဆိုပြီးသုံးတာရှိတယ်။
Java thread တခုကအနည်းဆုံး 1MB လောက်ကုန်တယ်။ အဲံတော့ 1000 concurrent thread ကို serve လုပ်မယ်ဆို 1GB လောက်ကသွားရော။
အဲ့လိုကိစ္စတွေရယ် နောက် synchronous က ဥပမာ ဒီလို run မယ်ဆိုပါစို့။
API 1
API 2
ခေါ်ရမယ်ဆိုပါစို့. API 1 ကိုခေါ်နေတဲ့အချိန် API2 ကိုခေါ်လို့မရဘူး။ concurrent လွှတ်မရဘူး အဲ့တော့ efficient မဖြစ်ဘူး။
Asynchronous က ခုနက API 1 ကိုလွှတ်တဲ့အချိန် API2 ကိုလဲ တခါတည်းလွှတ်လို့ရတယ်။ အဲ့တော့ပို efficient ဖြစ်တယ်ပေါ့။
ဒါပေသိ asynchronous မှာ execution order က ထိန်းရခက်တယ်။ callback hell ဘာညာ စသည်ဖြင့်။
အဲ့ကနောက်ဆုံး reactive model နဲ့ထုတ်လိုက်တယ်။ အဲ့တာ WebFlux ပဲ။
WebFlux က Node.js လို Event loop model ကိုသုံးတယ် ဆိုချင်တာက primary dispatcher က thread နည်းနည်းလေးပဲရှိတယ်။
Spring ReactorNetty လိုကောင်တွေမှာဆို Core ရှိသလောက်ပဲ ဥပမာ 8 core ရှိရင် Thread 8 ခုပဲ။
Async ဆိုတော့ main thread ကြီးကိုသွားပြီး block လုပ်လို့မရဘူး။တနည်းအားဖြင့် synchronous code မပြီးနိုင်မစီးနိုင်ကို သွား run လို့မရဘူး။
လုပ်မိရင်နောက်ထပ် request တွေက queue သွားလိမ့်မယ်။ အဲ့တော့ stack အားလုံး async ဖြစ်အောင်ရေးရတယ်။
ဥပမာ controller မှာ reactive ဖြစ်အောင် Mono, Flux နဲ့သုံးထားပြီးမှ db level ရောက်မှ synchronous driver သုံးထားတာက blocking call ပဲဖြစ်မှာ။
အဲ့တော့ ခုနက db ဘာညာလဲ nonblocking ဖြစ်အောင် reactive driver တွေ ပေးထားရတယ်။
နောက် တခြား API တွေ microservice တွေ ကိုခေါ်ဖို့အတွက်လဲ reactive ဖြစ်အောင် webclient ကိုလုပ်ပေးထားရသေးတယ်။
ပုံကတော့ credit


Original link