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

The Consumer API

Kafka consumer จะ subscribe topic แล้ว รัน consume loop — KafkaJS เรียก handler eachMessage ของคุณด้วย record จาก partition ที่ถูก assign ให้ และ loop ที่รันอยู่นี้เองที่คอยทำให้ consumer ยังมีชีวิตอยู่ใน group

คุณสร้าง consumer จาก Kafka client พร้อม groupId, connect(), subscribe() ไปยัง topic ที่ต้องการ แล้วเริ่ม run() KafkaJS จะส่งแต่ละ record ให้ callback eachMessage ของคุณ โดย key และ value มาเป็น Buffer ดิบ — คุณ deserialize เอง (เช่น .toString() หรือ JSON.parse) เป็นภาพสะท้อนของฝั่ง producer ที่ serialize

import { Kafka } from 'kafkajs';
const kafka = new Kafka({ clientId: 'order-processor', brokers: ['localhost:9092'] });
const consumer = kafka.consumer({ groupId: 'order-processor' }); // consumer group membership
async function main() {
await consumer.connect();
await consumer.subscribe({ topic: 'orders', fromBeginning: false }); // false = only new records (latest)
// run() drives the poll loop for you and calls eachMessage per record
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
// key/value are Buffers — deserialize them yourself
console.log(
`p=${partition} off=${message.offset} key=${message.key?.toString()} val=${message.value?.toString()}`,
);
},
});
}
main();

run() ทำมากกว่าแค่ดึงข้อมูล เบื้องหลังจะคอย poll Kafka, ส่ง heartbeat, เข้าร่วม group coordination และดึง partition assignment ให้ ถ้า eachMessage ของคุณ block นานเกินไป — process record หนึ่งนานกว่า session timeout — group coordinator จะถือว่า consumer ตายแล้ว และสั่ง rebalance ย้าย partition ไปให้ตัวอื่น กฎคือ คุมเวลา process ต่อ record ให้จำกัด

flowchart LR
  sub["subscribe(topics)"] --> run["consumer.run(...)"]
  run --> each["eachMessage per record"]
  each --> proc["process the record"]
  proc --> run
  run -->|also| hb["send heartbeats + coordinate group"]
The consumer run loop

message ทุกตัวเปิดเผย topic, partition, offset, key, value, timestamp และ headers ออกมา coordinate เหล่านี้คือสิ่งที่คุณใช้ commit ความคืบหน้า และใช้คิดเรื่องลำดับ — consumer จะเห็น record เรียงตาม offset ภายในแต่ละ partition แม้ว่า record จาก partition ต่างกันอาจสลับกันได้

consumer.run() (poll loop) ทำอะไรอีกนอกจากคืน record?
ถ้า consumer หยุด consume (handler block) นานเกินไปจะเกิดอะไรขึ้น?
จะได้ key หรือ value ที่มี type จาก message ของ KafkaJS ได้ยังไง?
consumer เห็น record เรียงตามลำดับแบบไหน?