Search code examples
javaspring-bootapache-kafkaapache-kafka-streamsspring-kafka

How to close KStream if all brokers are not available


I am using Kstreams with SpringBoot Application. If the Kafka is closed or it is Unreachable, only following is locked:

Connection to node -1 could not be established. Broker may not be available.

I want to close the application or atleast log the Exception if such condition occurs. Is there any way to do the same.


Solution

  • I added a CustomHealthIndicator that do the connection check continuously and if it found that the Kafka is unreachable it will throw exception and close the application.

    Sample Code is here:

    public class CustomHealthIndicator implements HealthIndicator {
        @Override
        public Health health() {
            return Health.up().withDetail("Status Code", "SUCCESS").build();
        }
    
        private void doHealthCheck() {
            Properties props = new Properties();
            props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, localhost:9092);
            AdminClient adminClient =  AdminClient.create(props);
            try {
                DescribeClusterOptions dco = new DescribeClusterOptions();
                dco.timeoutMs(30000);
                adminClient.describeCluster(dco).clusterId().get();
            } catch (Exception e) {
                System.exit(-1);
            } finally {
                adminClient.close();
                adminClient = null;
            }
        }
    
    }