Kafka Producer无法通过代码连接

u2nhd7ah  于 2023-10-15  发布在  Apache
关注(0)|答案(2)|浏览(88)

我无法通过代码连接到本地运行的Kafka示例-我可以使用Kafka-Console-Producer和Kafka-Console-Consumer成功连接,但当我使用Kafka Java SDK并简单地使用Java Producer连接到并生成任何消息时,它会失败并出现以下错误:

[Producer clientId=producer-1] Connection to node -1 (localhost/127.0.0.1:9092) could not be established. Broker may not be available.
[kafka-producer-network-thread | producer-1] WARN org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Bootstrap broker localhost:9092 (id: -1 rack: null) disconnected
[kafka-producer-network-thread | producer-1] WARN org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Connection to node -1 (localhost/127.0.0.1:9092) could not be established. Broker may not be available.
[kafka-producer-network-thread | producer-1] WARN org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Bootstrap broker localhost:9092 (id: -1 rack: null) disconnected
[kafka-producer-network-thread | producer-1] WARN org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Connection to node -1 (localhost/127.0.0.1:9092) could not be established. Broker may not be available.
[kafka-producer-network-thread | producer-1] WARN org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Bootstrap broker localhost:9092 (id: -1 rack: null) disconnected

不知道这是否重要,但我在Windows上使用WSL 2和Kafka 2.12-2.5.0来测试这一点。如何启用更详细的日志记录并调试它?
我的Producer代码的截图

Properties properties = new Properties();
properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

ProducerRecord<String, String> record = new ProducerRecord<String, String>("first_topic","first_value");

KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);
kafkaProducer.send(record);
kx5bkwkv

kx5bkwkv1#

抱歉,假警报。我的问题有点与WSL 2有关-我在Linux发行版的WSL 2中启动了我的ZK和Kafka Broker,但错误地试图从Windows中运行的Java应用程序访问Broker!
当我试图从Linux本身运行Java应用程序时。真的有用!

mgdq6dx1

mgdq6dx12#

当我试图从Windows上运行的IntelliJ Java应用程序连接到WSL 2下运行的Kafka Broker时,也遇到了同样的问题。
在这种情况下,解决方案是在WSL 2中禁用IPv6,以使其正常工作。根据官方Kafka在Windows上的WSL 2安装指南:
WSL 2目前有一个networking issue,可以防止外部程序连接到WSL 2上运行的Kafka(例如Java程序,Conduktor等);要解决这个问题,我们建议在WSL 2上禁用IPv6。第一个命令将提示您的Windows密码:

sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1
sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1

https://www.conduktor.io/kafka/how-to-install-apache-kafka-on-windows/

相关问题