本地Kafka集群写入失败:NotLeaderOrFollowerException报错求助
解决Kafka写入时的NotLeaderOrFollowerException错误
问题现象
执行生产者命令写入消息时报错:
echo "Hello, World" | ~/kafka/bin/kafka-console-producer.sh --broker-list localhost:9092 --topic TutorialTopic > /dev/null
错误日志片段:
[2023-08-17 02:35:07,842] WARN [Producer clientId=console-producer] Got error produce response with correlation id 4 on topic-partition TutorialTopic-0, retrying (2 attempts left). Error: NOT_LEADER_OR_FOLLOWER (org.apache.kafka.clients.producer.internals.Sender) ..... [2023-08-17 02:35:08,151] ERROR Error when sending message to topic TutorialTopic with key: null, value: 12 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback) org.apache.kafka.common.errors.NotLeaderOrFollowerException: For requests intended only for the leader, this error indicates that the broker is not the current leader. For requests intended for any replica, this error indicates that the broker is not a replica of the topic partition. ....
已完成的排查操作
- Listeners配置检查
执行命令:
$ cat /home/kafka/kafka/kafka.log | grep listeners
输出结果:
advertised.listeners = null early.start.listeners = null listeners = PLAINTEXT://localhost:9092
- 端口连通性验证
- 9092端口验证:
$ telnet localhost 9092
输出:
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. hi Connection closed by foreign host.
- 2181端口验证:
$ telnet localhost 2181
输出:
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. ruok imokConnection closed by foreign host.
- Topic信息查询
执行命令:
$ ~/kafka/bin/kafka-topics.sh --describe --topic TutorialTopic --bootstrap-server localhost:9092
输出结果:
Topic: TutorialTopic TopicId: rx7lEO7-RuOB-Uur_2lcAg PartitionCount: 1 ReplicationFactor: 1 Configs: Topic: TutorialTopic Partition: 0 Leader: 0 Replicas: 0 Isr: 0
解决方法
1. 配置advertised.listeners参数
当前日志显示advertised.listeners = null,这是核心问题。Kafka的advertised.listeners是对外暴露的Broker地址,客户端会通过ZooKeeper获取该地址建立连接,未配置会导致客户端无法正确连接到Leader节点。
修改Kafka配置文件(通常为server.properties):
advertised.listeners=PLAINTEXT://localhost:9092
保持和listeners参数值一致即可。
2. 重启Kafka服务
修改配置后,停止并重启Kafka:
# 停止Kafka ~/kafka/bin/kafka-server-stop.sh # 后台启动Kafka ~/kafka/bin/kafka-server-start.sh -daemon ~/kafka/config/server.properties
3. 验证修复效果
重新执行生产者命令,确认消息可正常写入:
echo "Hello, World" | ~/kafka/bin/kafka-console-producer.sh --broker-list localhost:9092 --topic TutorialTopic
同时可通过消费者命令验证消息接收:
~/kafka/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic TutorialTopic --from-beginning
额外排查点(若上述步骤无效)
- 检查ZooKeeper中Broker注册地址:
进入ZooKeeper客户端:
执行命令查看Broker详情:~/kafka/bin/zookeeper-shell.sh localhost:2181
确认返回的地址与get /brokers/ids/0advertised.listeners配置一致。 - 检查Kafka启动日志,排查是否存在Broker初始化异常、ZooKeeper连接失败等问题。
内容的提问来源于stack exchange,提问作者Ankitha N
相关产品推荐
相关产品推荐

