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

Headers & Choosing an 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"]
headers exchange match จากค่า header

routing ด้วย header ทรงพลังเมื่อเกณฑ์ของคุณเป็นหลายมิติจริง ๆ และยัดลงเป็น dotted string เส้นเดียวไม่ลงตัว แต่ในทางปฏิบัติ headers เป็น type ที่ ใช้น้อยที่สุด: routing key แบบ topic ที่ออกแบบดี ๆ มักสื่อเจตนาเดียวกันได้ง่ายกว่าและ match เร็วกว่า หยิบ headers มาใช้เฉพาะเมื่อ routing ขึ้นกับ attribute อิสระหลายตัวจริง ๆ

การตัดสินใจ routing ส่วนใหญ่จบได้ในตารางสั้น ๆ จับสิ่งที่คุณต้องการเข้ากับ type ที่ง่ายที่สุดที่สื่อสิ่งนั้น:

สิ่งที่คุณต้องการexchange typeทำอย่างไร
ปลายทางหมวดเดียวชัด ๆ ต่อ messagedirectbind ด้วย routing key เป๊ะ
broadcast ทุก message ไปทุก subscriberfanoutsubscriber แต่ละตัว bind queue ของตัวเอง
subscriber filter ด้วย pattern ยืดหยุ่นtopicbind ด้วย pattern * / # บน key แบบ dotted
route จาก attribute อิสระหลายตัวheadersbind ด้วยเงื่อนไข header + x-match

หลักคิดคร่าว ๆ:

  • เริ่มจาก type ที่ง่ายที่สุดที่ใช้ได้ ถ้า key เป๊ะตัวเดียวพอ ก็ใช้ direct อย่าเผื่อไปหยิบ topic แบบเก็งกำไร
  • event bus ให้ default เป็น topic topic ครอบคลุมทั้ง direct และ fanout คุณจึงเหลือที่เพิ่ม subscriber ที่ละเอียดขึ้นได้โดยไม่ต้องแก้ producer
  • เลี่ยง headers เว้นแต่จำเป็นจริง ๆ routing key แบบ dotted ที่ดีเกือบทุกครั้งเอาชนะ headers เรื่องความชัดและความเร็ว
  • ออกแบบ routing-key scheme แต่เนิ่น ๆ domain.detail.action (เช่น order.eu.created) คือ convention ที่ควรตกลงกันก่อน producer ตัวแรกจะขึ้น
headers exchange route จากอะไร?
headers binding ใช้ "x-match: any" message จะ match เมื่อ:
exchange type ไหนเป็น default ที่ดีที่สุดสำหรับ event bus ที่ยืดหยุ่น?
ทำไม headers exchange ถึงถูกใช้น้อยในทางปฏิบัติ?