Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Ruby

เข้าใจ Application Servers ใน Ruby: ทำไม Puma จึงสำคัญ

rails server ตอนรันแล้ว "Puma" ก็ขึ้นมาวิ่ง — มันคืออะไร?

มันคือ App Server!

มาอธิบาย Application Server คืออะไร ทำไมต้องมี พร้อมตัวอย่าง

เข้าใจ App Servers

สมมติเริ่มสร้าง Web App ใหม่ใน Ruby — ก่อนเขียนโค้ดอยากเห็น Load ใน Browser แม้แค่ Default "Welcome" Page

เปิด Browser ชี้ที่ localhost:3000 (หรือ localhost:4567 ถ้า Sinatra)

เกิดอะไรขึ้น?

Browser Connect ไป localhost Port 3000 ที่ Ruby App Server เช่น Puma รออยู่

localhost ชี้ IP พิเศษ 127.0.0.1 หมายถึงเครื่องคุณเสมอ

ตอนนี้: หน้าที่ Puma (หรือ Rack-based Servers อื่นๆ เช่น Thin/Unicorn) คือ Handle Request ของ Browser แล้วส่งต่อให้ App ผ่าน Common Interface

Interface อะไร? Rack (อธิบายละเอียดในบทความอื่น) — กลับมาที่ Puma

ทำไมต้อง App Server แทนที่จะให้ Rails Handle Requests ตรงๆ? คำถามดี!

เพราะมันทำให้ได้หลักการออกแบบพื้นฐาน: Separation of Concerns (การแยกความกังวล)

เข้าใจ Separation of Concerns

หน้าที่ Rails และ App คือ Serve User Request — เช่น: สร้าง Account, Check Login, แสดงหน้าสินค้า

  • Raws เสนอ Menu สิ่งที่ User ทำได้ แต่ก็คือ Chef ที่ทำจริง
  • Puma คือ Waiter รับ Order ส่งให้ครัว

Setup แบบนี้ให้ทุกฝ่ายทำหน้าที่ได้เต็มที่ — ไม่ chỉนั้น... ยังสลับ Chef เป็น Sinatra หรือ Waiter เป็น Thin ได้!

"When concerns are well-separated, there are higher degrees of freedom for module reuse as well as independent development and upgrade."
Wikipedia

ขึ้นอยู่กับ Situation และ Preferences

Application Server vs Web Server (Nginx & Apache)

อาจสงสัย... Web Server อย่าง Apache/Nginx ต่างจาก Ruby Server ยังไง? ทำไมไม่ใช้ 2 ตัวนี้?

ต่างกันมาก — Nginx เป็น General Webserver Handle Request ถ้ามี File ตรง Request จะ Return File

แต่ Nginx ไม่รู้จัก Rack และ Ruby — ต้องมี Puma หรือ Rack-compatible Server

แต่... ใช้ Nginx ใน Production ยังช่วยได้ — Handle Connections ได้ดีกว่า และ Serve Static Assets (CSS/JS) โดยไม่ส่งต่อให้ App

เข้าใจ Puma

ตอนเข้าใจ App Server แล้ว — มาดู Puma เอง ทำไมเลือก Puma แทน Server อื่น?

First: Heroku Recommended Server — เหตุผลหลัก: ถ้าใช้ Unicorn (Alternative) ถูก Slow Client Attacks

Also: Puma Multi-threaded — ปกติแล้ว Memory Usage น้อยกว่า

"The operating system performs less work on behalf of a multithreaded program than it does for a multiprocess program. This translates into a performance gain for the multithreaded program."
PThreads Programming

Server ไหนเร็วที่สุด?

รัน Simple Rack App ด้วย:

 rackup -s thin rack-simple.ru 2>1 &>/dev/null 

Test ด้วย:

 wrk -d 20 https://localhost:9292 

Benchmark Results:

  • Webrick: 229.97 req/sec
  • Thin: 773.20 req/sec
  • Puma: 2035.34 req/sec

ดูเหมือน Puma ให้ Performance ดีสุด — แต่มันไม่สำคัญถ้ามี Slow SQL Query หรือ Loop Arrays ล้านๆ ทุก Request

Summary (สรุป)

คุณเรียนรู้ Application Servers ใน Ruby เช่น Puma และ Thin — เข้าใจดีขึ้นว่าทำไมต้องใช้พวกเขา

เข้าใจ Application Servers ใน Ruby: ทำไม Puma จึงสำคัญ

โปรเจกต์หน้าใช้ตัวไหน?

ขอบคุณที่อ่าน! 🙂