java 连接k8s中kafka 生产消息 出现 Could not login: the client is being asked for a password, but the Kafka client code does not currently support obtaining a password from the user. not available to garner authentication information from the user
时间: 2024-03-27 09:36:05 浏览: 138
kafka调试中遇到Connection to node -1 could not be established. Broker may not be available.
5星 · 资源好评率100%
这个问题是因为你的 Kafka broker 配置了 SASL/PLAIN 认证,但是你的 Kafka 客户端连接 broker 时并没有提供认证信息,导致连接失败。解决这个问题的方法是在客户端代码中提供 SASL/PLAIN 认证信息,包括用户名和密码。
以下是 Java 连接 Kafka 的示例代码,其中包括了 SASL/PLAIN 认证信息的设置:
```java
import org.apache.kafka.clients.producer.*;
import java.util.Properties;
public class KafkaProducerExample {
public static void main(String[] args) throws Exception{
String topicName = "test-topic";
String kafkaServer = "localhost:9092";
String username = "your_kafka_username";
String password = "your_kafka_password";
Properties props = new Properties();
props.put("bootstrap.servers", kafkaServer);
props.put("security.protocol", "SASL_PLAINTEXT");
props.put("sasl.mechanism", "PLAIN");
props.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"" + username + "\" password=\"" + password + "\";");
Producer<String, String> producer = new KafkaProducer<>(props);
for (int i = 0; i < 10; i++)
producer.send(new ProducerRecord<>(topicName,
Integer.toString(i), Integer.toString(i)));
producer.close();
}
}
```
这个示例代码中,我们使用了 Kafka 的 SASL_PLAINTEXT 认证协议,并提供了用户名和密码,这样就可以成功连接 Kafka broker 并发送消息了。
阅读全文