自定义 Kafka Binder 健康指标

重写默认Kafka绑定器健康状况指示器

当 Spring Boot 监管器在类路径中时,Kafka 绑定程序会激活一个默认的健康指标。 此健康指标检查绑定程序的健康状态以及与 Kafka 代理的任何通信问题。 如果应用程序想要禁用此默认的健康检查实现并包含自定义实现,则可以提供对KafkaBinderHealth接口的实现。 KafkaBinderHealth是扩展自HealthIndicator的标记接口。
在自定义实现中,必须为health()方法提供实现。
自定义实现必须作为应用程序配置中的 Bean 提供。
当绑定程序发现自定义实现时,它将使用该实现而不是默认实现。
这是应用程序中此类自定义实现 Bean 的示例。spring-doc.cadn.net.cn

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

自定义 kafka 绑定程序健康指标示例

这里是为编写自定义 Kafka binder HealthIndicator 的伪代码。 在这个示例中,我们尝试通过首先检查集群连接性,然后检查与主题相关的其他问题来覆盖 Kafka HealthIndicator。spring-doc.cadn.net.cn

首先,我们需要创建一个自定义实现KafkaBinderHealth接口。spring-doc.cadn.net.cn

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。spring-doc.cadn.net.cn

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