springboot接⼊Prometheus实现⾃定义指标
前⾔
⽬前翻阅了⽹上的各种代码集成Prometheus的demo,千篇⼀律,基本都是复制粘贴,均是1.x版本的springboot且代码都是跑不通的。现根据开源依赖debug源码,实践出可⽤版本。
完整代码地址
此代码亲测可⽤。
版本
io.micrometer 1.2.1springboot和过滤器
springboot 2.0.5.RELEASE
本代码实现功能
1.Java接⼊Prometheus,提供JVM监控及⾃定义指标监控
2.实现⾃定义指标的接⼊功能
3.实现指标label动态赋值功能
代码⽚段
compile "io.prometheus:simpleclient_hotspot:0.0.24"
compile "io.micrometer:micrometer-registry-prometheus:1.2.1"
compile "io.micrometer:micrometer-core:1.2.1"
注册MeterRegistry
@Bean(value = "meterRegistryCustomizer")
MeterRegistryCustomizer<MeterRegistry> meterRegistryCustomizer() {
return meterRegistry -> fig()
monTags("application", "springboot-app");
}
MyMetrics ⾃定义指标
/**
* 计数器可以⽤于记录只会增加不会减少的指标类型,⽐如记录应⽤请求的总量(http_requests_total),
* cpu使⽤时间(process_cpu_seconds_total)等。⼀般⽽⾔,Counter类型的metrics指标在命名中
* 我们使⽤_total结束。
*/
public static Counter requestCounter = Counter.build()
.name("io_namespace_http_requests_total")
.labelNames("path", "method", "code")
.help("Total requests.").register();
注册⾃定义指标
@Component
public class InitPrometheus implements ApplicationListener<ContextRefreshedEvent> {
@Resource
PrometheusMeterRegistry meterRegistry;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
new MyMetrics();
CollectorRegistry prometheusRegistry = PrometheusRegistry();
}
}
使⽤
配置
@Configuration
public class AppConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new PrometheusMetricsInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
为指标赋值
public class PrometheusMetricsInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = RequestURI();
String method = Method();
int status = Status();
MyMetrics.inprogressRequests.labels(requestURI,method).inc();
MyMetrics.histogramRequestTimer = questLatencyHistogram.labels(requestURI, method, String.valueOf(status)).startTimer();        questTimer = questLatency.labels(requestURI, method, String.valueOf(status)).startTimer();
return super.preHandle(request, response, handler);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
String requestURI = RequestURI();
String method = Method();
int status = Status();
MyMetrics.inprogressRequests.labels(requestURI,method).dec();
MyMetrics.histogramRequestTimer.observeDuration();
super.afterCompletion(request, response, handler, ex);
}
}
启动项⽬,查看服务指标信息
localhost:8502/metrics/prometheus

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。