'Connect to Kafka running in WSL2 Ubuntu

The below are my Kafka broker configuration

broker.id=1
port=9092
host.name=127.0.0.1
advertised.listeners=PLAINTEXT://127.0.0.1:9092
listeners=PLAINTEXT://127.0.0.1:9092

Console producer and consumer are working perfectly but when I try to connect through java, it is throwing broker not available error. But Kafka broker is running and able to produce and consume messages through console.

Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

KafkaProducer<String, String> producer = new KafkaProducer<String,String>(props);

producer.send(new ProducerRecord<String, String>("Sample","Hey","From java program"));
producer.close();
[kafka-producer-network-thread | producer-1] WARN org.apache.kafka.clients.NetworkClient - [Producer clientId=producer-1] Connection to node -1 (/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 127.0.0.1:9092 (id: -1 rack: null) disconnected

I'm using STS IDE to write java program and using JDK 1.8, kafka 2.8.1 windows OS and using ubuntu 20.04.4 LTS to execute console producer and consumer.

Thanks in advance !



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source