I am playing with a Kafka for Java tutorial. I have concocted the following code:
Producer class
public class ProducerDemo {
static String bootstrapServers = "127.0.0.1:9092";
public static void main(String[] args) {
// create producer properties
Properties properties = new Properties();
properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
// create producer
KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
// create ProducerRecord
ProducerRecord<String, String> record = new ProducerRecord<>("first_topic", "hello world!");
// send data
producer.send(record);
producer.close();
}
}
Gradle file
plugins {
id 'java'
}
group 'com.greem666.kafka'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
compileOnly 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'
testCompileOnly 'org.projectlombok:lombok:1.18.20'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.20'
implementation group: 'org.apache.kafka', name: 'kafka-clients', version: '2.8.0'
implementation group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.30'
}
I have a kafka_2.13-2.8.0 Zookeeper and one Broker running in a WSL2 instance on the same Win10 machine. When trying to play with console Consumer and console Producer in WSL2, it all works fine.
However, when I try to run the above Java class, I get this:
Java logs
[main] INFO org.apache.kafka.common.utils.AppInfoParser - Kafka version: 2.8.0
[main] INFO org.apache.kafka.common.utils.AppInfoParser - Kafka commitId: ebb1d6e21cc92130
[main] INFO org.apache.kafka.common.utils.AppInfoParser - Kafka startTimeMs: 1623940023993
[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
Any ideas why this is happening? Does it have something to do with Kafka Zookeeper and Broker running in a WSL2?
localhostis not exactly the same as127.0.0.1. Did you try actually usinglocalhost?