以生产者为例介绍spring如何整合kafka-clients,micrometer,prometheus。上报生产者监控打点
可以通过在Spring Boot应用中手动添加Kafka Producer的度量监控,确保Prometheus能够采集到Producer的指标。以下是一个示例代码,其中使用了MeterRegistry
注册Kafka Producer的度量指标:
1. 引入依赖
确保在pom.xml
中引入Micrometer和Prometheus相关的依赖:
xml
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
2. 配置Kafka和Prometheus监控
在配置类中,手动为Producer添加度量注册。
java
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.binder.kafka.KafkaMetrics;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class KafkaProducerConfig {
@Bean
public KafkaProducer<String, String> kafkaProducer() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.METRICS_RECORDING_LEVEL_CONFIG, "INFO"); // 启用INFO级别的监控
return new KafkaProducer<>(configProps);
}
@Bean
public MeterBinder kafkaProducerMetrics(KafkaProducer<String, String> kafkaProducer) {
return new KafkaMetrics(kafkaProducer);
}
}
3. 配置Prometheus端点
在application.yml
中配置Prometheus的端点:
yaml
management:
endpoints:
web:
exposure:
include: "*"
metrics:
export:
prometheus:
enabled: true
endpoint:
prometheus:
enabled: true
4. 配置Prometheus采集
确保Prometheus的配置文件中包含Spring Boot应用的Prometheus端点,通常是http://<application-host>:<port>/actuator/prometheus
。
5. 使用Producer并触发度量
在应用代码中使用KafkaProducer
发送消息,以确保Producer的指标数据生成:
java
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class KafkaProducerService {
private final KafkaProducer<String, String> producer;
@Autowired
public KafkaProducerService(KafkaProducer<String, String> producer) {
this.producer = producer;
}
public void sendMessage(String topic, String key, String value) {
ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
producer.send(record);
}
}
6. 验证
运行应用并访问http://<application-host>:<port>/actuator/prometheus
,检查是否包含Producer的指标数据。这样Prometheus应该能够采集到Producer的度量指标。