ข้ามไปยังเนื้อหา

Service Definition

โมดูล Protocol Buffers ให้ คำนาม กับคุณไปแล้ว — message คือรูปร่างของข้อมูล โมดูลนี้ให้ คำกริยา: service คือกลุ่มของ method (rpc) ที่ตั้งชื่อไว้ และแต่ละ method รับ request message เข้าไปหนึ่งตัว ส่ง response message ออกมาหนึ่งตัว

การตัดสินใจแค่จุดเดียวนี้ — method ไม่ใช่ resource — คือสิ่งที่ทำให้ฝั่ง client รู้สึกเหมือนเรียก function ในเครื่องตัวเอง ในโมดูลนี้ทุกอย่างมารวมกันเป็นหน้าตา API จริง ๆ

บทเรียนสิ่งที่คุณจะได้เรียนรู้
Defining Servicessyntax ของ service และ rpc, การตั้งชื่อ package และการทำ API versioning ใน package path
The Four RPC Typesunary, server-streaming, client-streaming, bidirectional — และ message flow ของแต่ละแบบ
Designing Methodswrapper request/response message, การตั้งชื่อ, pagination และ idempotency
Errors & Status Codesstatus code model และ rich error ด้วย google.rpc.Status
flowchart LR
  subgraph svc["service UserService"]
    m1["rpc GetUser(GetUserRequest) → User"]
    m2["rpc CreateUser(CreateUserRequest) → User"]
    m3["rpc ListUsers(ListUsersRequest) → ListUsersResponse"]
  end
  client["client stub"] -->|calls| svc
  svc -->|typed response| client
service รวม method หลายตัว แต่ละ method map request ไปเป็น response

พอจบโมดูลนี้ คุณจะอ่าน service block ใน .proto ตัวไหนก็ได้แล้วรู้ทันทีว่ามี call อะไรบ้าง อันไหน stream และรายงาน failure อย่างไร

gRPC `service` คืออะไร?
unary rpc หนึ่งตัวรับและส่ง message กี่ตัว?
อะไรคือกรอบคิดที่ทำให้ gRPC service ต่างจาก REST?