[英]Waiting for leadership elections in KafkaJS
我正在使用kafkajs寫入一些動態生成的 kafka 主題。
我發現在注冊我的生產者后立即寫這些主題會經常導致錯誤: There is no leader for this topic-partition as we are in the middle of a leadership election
。
完整的錯誤是:
{"level":"ERROR","timestamp":"2020-08-24T17:48:40.201Z","logger":"kafkajs","message":"[Connection] Response Metadata(key: 3, version: 5)","broker":"localhost:9092","clientId":"tv-kitchen","error":"There is no leader for this topic-partition as we are in the middle of a leadership election","correlationId":1,"size":146}
這是導致問題的代碼:
import kafka from 'myConfiguredKafkaJs'
const run = async () => {
const producer = kafka.producer()
await producer.connect()
producer.send({
topic: 'myRandomTopicString',
messages: [{
value: 'yolo',
}],
})
}
run()
兩個問題:
Kafkajs 通過管理客戶端提供了一個createTopics
方法,該方法有一個可選的waitForLeaders
標志:
admin.createTopics({
waitForLeaders: true,
topics: [
{ topic: 'myRandomTopicString123' },
],
}
使用它可以解決問題。
import kafka from 'myConfiguredKafkaJs'
const run = async () => {
const producer = kafka.producer()
const admin = kafka.admin()
await admin.connect()
await producer.connect()
await admin.createTopics({
waitForLeaders: true,
topics: [
{ topic: 'myRandomTopicString123' },
],
})
producer.send({
topic: 'myRandomTopicString',
messages: [{
value: 'yolo',
}],
})
}
run()
不幸的是,如果主題已經存在,這將導致不同的錯誤,但這是一個單獨的問題,我懷疑錯誤比破壞更具信息性。
{"level":"ERROR","timestamp":"2020-08-24T18:19:48.465Z","logger":"kafkajs","message":"[Connection] Response CreateTopics(key: 19, version: 2)","broker":"localhost:9092","clientId":"tv-kitchen","error":"Topic with this name already exists","correlationId":2,"size":86}
編輯:上述設置確實需要正確配置您的 Kafka 實例。 有可能領導選舉永遠不會解決,在這種情況下 KafkaJS 仍然會抱怨領導選舉!
根據我的經驗,這是由於 kafka 代理在沒有從 Zookeeper 注銷的情況下被停止的情況,這意味着 Zookeeper 正在等待不再存在的東西的響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.