博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Grafana+Prometheus系统监控之SpringBoot
阅读量:7216 次
发布时间:2019-06-29

本文共 5313 字,大约阅读时间需要 17 分钟。

hot3.png

前言

前一段时间使用SpringBoot创建了一个,由于近期项目中也使用了不少SpringBoot相关的项目,趁着周末,配置一下使用prometheus监控微服务Springboot。

项目配置

引入坐标

io.prometheus
simpleclient_spring_boot
0.1.0
io.prometheus
simpleclient_hotspot
0.1.0
io.prometheus
simpleclient_servlet
0.1.0

配置Application

@SpringBootApplication@EnablePrometheusEndpoint@EnableSpringBootMetricsCollectorpublic class Application  {    private static final Logger logger = LoggerFactory.getLogger(Application.class);    public static void main(String[] args) throws InterruptedException {        SpringApplication.run(Application.class, args);        logger.info("项目启动 ");    }}

配置MonitoringConfig

@Configurationclass MonitoringConfig {    @Bean    SpringBootMetricsCollector springBootMetricsCollector(Collection
publicMetrics) { SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics); springBootMetricsCollector.register(); return springBootMetricsCollector; } @Bean ServletRegistrationBean servletRegistrationBean() { DefaultExports.initialize(); return new ServletRegistrationBean(new MetricsServlet(), "/prometheus"); }}

配置Interceptor

RequestCounterInterceptor(计数):

public class RequestCounterInterceptor extends HandlerInterceptorAdapter {    // @formatter:off    // Note (1)    private static final Counter requestTotal = Counter.build()         .name("http_requests_total")         .labelNames("method", "handler", "status")         .help("Http Request Total").register();    // @formatter:on    @Override    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)                                                                                                         throws Exception {         // Update counters         String handlerLabel = handler.toString();         // get short form of handler method name         if (handler instanceof HandlerMethod) {              Method method = ((HandlerMethod) handler).getMethod();              handlerLabel = method.getDeclaringClass().getSimpleName() + "." + method.getName();         }         // Note (2)         requestTotal.labels(request.getMethod(), handlerLabel, Integer.toString(response.getStatus())).inc();    }}

RequestTimingInterceptor(统计请求时间):

package com.itstyle.webhook.interceptor;import java.lang.reflect.Method;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import io.prometheus.client.Summary;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;public class RequestTimingInterceptor extends HandlerInterceptorAdapter {    private static final String REQ_PARAM_TIMING = "timing";    // @formatter:off    // Note (1)    private static final Summary responseTimeInMs = Summary         .build()         .name("http_response_time_milliseconds")         .labelNames("method", "handler", "status")         .help("Request completed time in milliseconds")         .register();    // @formatter:on    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {         // Note (2)         request.setAttribute(REQ_PARAM_TIMING, System.currentTimeMillis());         return true;    }    @Override    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {         Long timingAttr = (Long) request.getAttribute(REQ_PARAM_TIMING);         long completedTime = System.currentTimeMillis() - timingAttr;         String handlerLabel = handler.toString();         // get short form of handler method name         if (handler instanceof HandlerMethod) {              Method method = ((HandlerMethod) handler).getMethod();              handlerLabel = method.getDeclaringClass().getSimpleName() + "." + method.getName();         }       // Note (3)       responseTimeInMs.labels(request.getMethod(), handlerLabel,                                Integer.toString(response.getStatus())).observe(completedTime);    }}

配置Controller

主要是为了测试拦截器的效果

@RestControllerpublic class HomeController {     private static final Logger logger = LoggerFactory.getLogger(HomeController.class);      @RequestMapping("/endpointA")     public void handlerA() throws InterruptedException {          logger.info("/endpointA");          Thread.sleep(RandomUtils.nextLong(0, 100));     }      @RequestMapping("/endpointB")     public void handlerB() throws InterruptedException {          logger.info("/endpointB");          Thread.sleep(RandomUtils.nextLong(0, 100));     }}

以上都配置完成后启动项目即可。

配置Prometheus

vi prometheus.yml

- job_name: webhook    metrics_path: '/prometheus'    static_configs:     - targets: ['localhost:8080']       labels:         instance: webhook

保存后重新启动Prometheus即可。

访问 服务State 为up说明配置成功,查阅很多教程都说需要配置 spring.metrics.servo.enabled=false,否则在prometheus的控制台的targets页签里,会一直显示此endpoint为down状态,然貌似并没有配置也是ok的。

2

访问 测试一下效果

1

配置Grafana

如图所示:

3

参考链接

作者: 小柒

出处: 

转载于:https://my.oschina.net/xiaominmin/blog/1788573

你可能感兴趣的文章
rhel6.2配置在线yum源
查看>>
分级聚类算法
查看>>
Web Services 入门(之二)
查看>>
随机模拟MCMC和Gibbs Sampling
查看>>
网络安全是一种态度
查看>>
POJ1131 Octal Fractions
查看>>
mysql-ulogd2.sql
查看>>
119. Pascal's Triangle II - Easy
查看>>
349. Intersection of Two Arrays - Easy
查看>>
[算法练习]最长公共子串(LCS)
查看>>
p转c++
查看>>
树(tree)
查看>>
codevs——2645 Spore
查看>>
ssh服务之 远程登录和端口转发
查看>>
java环境配置正确,但是tomcat不能启动的解决办法
查看>>
我就是想找个人聊聊天,说说我这近四年来的经历
查看>>
不同的测试方法使用的场景
查看>>
Hadoop快速入门
查看>>
Problem S
查看>>
SVN上传的时候没法显示文件名,只显示后缀名
查看>>