自定义 Kafka 绑定器健康指示器

覆盖默认 Kafka 绑定器健康指示器

当 Spring Boot actuator 存在于 classpath 中时,Kafka 绑定器会激活一个默认的健康指示器。 此健康指示器检查绑定器的健康状况以及与 Kafka 代理的任何通信问题。 如果应用程序希望禁用此默认健康检查实现并包含自定义实现,则可以为 KafkaBinderHealth 接口提供一个实现。 KafkaBinderHealth 是一个扩展自 HealthIndicator 的标记接口。 在自定义实现中,它必须提供 health() 方法的实现。 自定义实现必须作为 bean 存在于应用程序配置中。 当绑定器发现自定义实现时,它将使用该实现而不是默认实现。 以下是应用程序中此类自定义实现 bean 的示例。

@Bean
public KafkaBinderHealth kafkaBinderHealthIndicator() {
    return new KafkaBinderHealth() {
        @Override
        public Health health() {
            // custom implementation details.
        }
    };
}

自定义 Kafka 绑定器健康指示器示例

以下是编写自定义 Kafka 绑定器 HealthIndicator 的伪代码。 在此示例中,我们尝试通过首先检查集群连接,然后检查与主题相关的问题来覆盖绑定器提供的 Kafka HealthIndicator。

首先,我们需要创建 KafkaBinderHealth 接口的自定义实现。

public class KafkaBinderHealthImplementation implements KafkaBinderHealth {
    @Value("${spring.cloud.bus.destination}")
    private String topic;
    private final AdminClient client;

    public KafkaBinderHealthImplementation(final KafkaAdmin admin) {
		// More about configuring Kafka
		// https://docs.spring.io/spring-kafka/reference/html/#configuring-topics
        this.client = AdminClient.create(admin.getConfigurationProperties());
    }

    @Override
    public Health health() {
        if (!checkBrokersConnection()) {
            logger.error("Error when connect brokers");
			return Health.down().withDetail("BrokersConnectionError", "Error message").build();
        }
		if (!checkTopicConnection()) {
			logger.error("Error when trying to connect with specific topic");
			return Health.down().withDetail("TopicError", "Error message with topic name").build();
		}
        return Health.up().build();
    }

    public boolean checkBrokersConnection() {
        // Your implementation
    }

    public boolean checkTopicConnection() {
		// Your implementation
    }
}

然后我们需要为自定义实现创建一个 bean。

@Configuration
public class KafkaBinderHealthIndicatorConfiguration {
	@Bean
	public KafkaBinderHealth kafkaBinderHealthIndicator(final KafkaAdmin admin) {
		return new KafkaBinderHealthImplementation(admin);
	}
}