Connection to node -1 (localhost/127.0.0.1:9092) could not be established. broker may not be available.

When you encounter the error “connection to node -1 (localhost/127.0.0.1:9092) could not be established. broker may not be available.”, it means that your Kafka broker is not running or is not accessible at the specified address and port.

This error commonly occurs due to the following reasons:

  1. The Kafka broker is not started or has crashed.
  2. The specified address and port are incorrect.
  3. There might be a network issue preventing the connection.

To fix this issue, you can follow these steps:

  1. Ensure that the Kafka broker is running. Start it if necessary.
  2. Check that the address and port provided in the connection configuration are correct. The default address is typically localhost or 127.0.0.1, and the default port is 9092.
  3. Verify there are no network connectivity issues between the client and the broker. Ensure that the client can reach the broker’s address and port. You can test the connection using tools like telnet or curl.

Here’s an example code snippet demonstrating how to connect to a Kafka broker using the Kafka Java client library:

    
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.DescribeClusterOptions;
import org.apache.kafka.clients.admin.DescribeClusterResult;
import org.apache.kafka.common.KafkaFuture;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class KafkaConnectionExample {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");

        AdminClient adminClient = AdminClient.create(properties);

        DescribeClusterOptions options = new DescribeClusterOptions().timeoutMs(5000);
        DescribeClusterResult result = adminClient.describeCluster(options);
        
        try {
            KafkaFuture clusterIdFuture = result.clusterId();
            String clusterId = clusterIdFuture.get();
            
            System.out.println("Connected to Kafka cluster with ID: " + clusterId);
        } catch (InterruptedException | ExecutionException e) {
            System.err.println("Failed to connect to Kafka broker: " + e.getMessage());
        }
        
        adminClient.close();
    }
}
    
  

Same cateogry post

Leave a comment