Headers & Choosing an Exchange
headers exchange
หัวข้อที่มีชื่อว่า “headers exchange”headers exchange ไม่สนใจ routing key เลย และ route จาก header ของ message — คู่ key/value ใน message properties แต่ละ binding ระบุ header ที่ message ต้องพกมาจึงจะ match บวกกับ argument พิเศษ x-match:
x-match: all— message ต้องมี header ทุกตัว ใน binding (logical AND)x-match: any— message ต้องมี อย่างน้อยหนึ่งตัว (logical OR)
ตัวอย่างเช่น binding { format: "pdf", type: "report", x-match: "all" } จะ match เฉพาะ message ที่ header มีทั้ง format=pdf และ type=report
flowchart LR
p["publish
headers: {format: pdf, type: report}"] --> x["headers exchange"]
x -->|"x-match: all
format=pdf, type=report"| q1["queue: pdf-reports"]
x -. "x-match: all
format=png" .-> q2["queue: images"] routing ด้วย header ทรงพลังเมื่อเกณฑ์ของคุณเป็นหลายมิติจริง ๆ และยัดลงเป็น dotted string เส้นเดียวไม่ลงตัว แต่ในทางปฏิบัติ headers เป็น type ที่ ใช้น้อยที่สุด: routing key แบบ topic ที่ออกแบบดี ๆ มักสื่อเจตนาเดียวกันได้ง่ายกว่าและ match เร็วกว่า หยิบ headers มาใช้เฉพาะเมื่อ routing ขึ้นกับ attribute อิสระหลายตัวจริง ๆ
เลือก exchange type
หัวข้อที่มีชื่อว่า “เลือก exchange type”การตัดสินใจ routing ส่วนใหญ่จบได้ในตารางสั้น ๆ จับสิ่งที่คุณต้องการเข้ากับ type ที่ง่ายที่สุดที่สื่อสิ่งนั้น:
| สิ่งที่คุณต้องการ | exchange type | ทำอย่างไร |
|---|---|---|
| ปลายทางหมวดเดียวชัด ๆ ต่อ message | direct | bind ด้วย routing key เป๊ะ |
| broadcast ทุก message ไปทุก subscriber | fanout | subscriber แต่ละตัว bind queue ของตัวเอง |
| subscriber filter ด้วย pattern ยืดหยุ่น | topic | bind ด้วย pattern * / # บน key แบบ dotted |
| route จาก attribute อิสระหลายตัว | headers | bind ด้วยเงื่อนไข header + x-match |
หลักคิดคร่าว ๆ:
- เริ่มจาก type ที่ง่ายที่สุดที่ใช้ได้ ถ้า key เป๊ะตัวเดียวพอ ก็ใช้
directอย่าเผื่อไปหยิบtopicแบบเก็งกำไร - event bus ให้ default เป็น
topictopic ครอบคลุมทั้ง direct และ fanout คุณจึงเหลือที่เพิ่ม subscriber ที่ละเอียดขึ้นได้โดยไม่ต้องแก้ producer - เลี่ยง
headersเว้นแต่จำเป็นจริง ๆ routing key แบบ dotted ที่ดีเกือบทุกครั้งเอาชนะ headers เรื่องความชัดและความเร็ว - ออกแบบ routing-key scheme แต่เนิ่น ๆ
domain.detail.action(เช่นorder.eu.created) คือ convention ที่ควรตกลงกันก่อน producer ตัวแรกจะขึ้น