Springboot of Grafana+prometheus system monitoring

Source: Internet
Author: User
Tags time in milliseconds grafana webhook

Objective

A time ago, a Webhook project was created using Springboot, and as a result of recent projects, a number of springboot related projects were used, while the weekend was configured to use Prometheus to monitor micro-service springboot.

Project configuration Introduction coordinates
<!--exposition Spring_boot --<dependency>    <groupId>Io.prometheus</groupId>    <artifactId>Simpleclient_spring_boot</artifactId>    <version>0.1.0</version></dependency><!--Hotspot JVM metrics --<dependency>    <groupId>Io.prometheus</groupId>    <artifactId>Simpleclient_hotspot</artifactId>    <version>0.1.0</version></dependency><!--exposition servlet ---<dependency>    <groupId>Io.prometheus</groupId>    <artifactId>Simpleclient_servlet</artifactId>    <version>0.1.0</version></dependency>
Configure Application
@SpringBootApplication@EnablePrometheusEndpoint@EnableSpringBootMetricsCollectorpublicclass Application  {    privatestaticfinal Logger logger = LoggerFactory.getLogger(Application.class);    publicstaticvoidmainthrows InterruptedException {        SpringApplication.run(Application.class, args);        logger.info("项目启动 ");    }}
Configure Monitoringconfig
 @Configuration  class  monitoringconfig { @Bean  springbootmetricscollector  (collection<publicmetrics> publicmetrics) {springbootmetricscollector spri Ngbootmetricscollector = new  springbootmetricscollector  ( Publicmetrics); Springbootmetricscollector. register  (); return  springbootmetricscollector; }  @Bean  servletregistrationbean servletregistrationbean  () {D Efaultexports. initialize  (); return  new  servletregistrationbean  (new  metricsservlet  (), ); }}
Configure Interceptor

Requestcounterinterceptor (count):

 Public classRequestcounterinterceptorextendsHandlerinterceptoradapter {//@formatter: Off    //Note (1)    Private Static FinalCounter 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)throwsException {//Update countersString Handlerlabel = handler.toString();//Get short form of handler method name         if(HandlerinstanceofHandlermethod) {Method method = ((Handlermethod) handler).GetMethod(); Handlerlabel = method.Getdeclaringclass().Getsimplename() +"."+ method.GetName(); }//Note (2)Requesttotal.Labels(Request.GetMethod(), Handlerlabel, Integer.toString(Response.GetStatus())).Inc(); }}

Requesttiminginterceptor (Statistical request time):

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 classRequesttiminginterceptorextendsHandlerinterceptoradapter {Private Static FinalString req_param_timing ="Timing";//@formatter: Off    //Note (1)    Private Static FinalSummary 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)throwsException {//Note (2)Request.SetAttribute(Req_param_timing, System.)Currenttimemillis());return true; }@Override     Public void aftercompletion(HttpServletRequest request, httpservletresponse response, Object handler, Exception ex)throwsException {Long timingattr = (long) request.getattribute(req_param_timing);LongCompletedtime = System.Currenttimemillis()-timingattr; String Handlerlabel = handler.toString();//Get short form of handler method name         if(HandlerinstanceofHandlermethod) {Method method = ((Handlermethod) handler).GetMethod(); Handlerlabel = method.Getdeclaringclass().Getsimplename() +"."+ method.GetName(); }//Note (3)Responsetimeinms.Labels(Request.GetMethod(), Handlerlabel, Integer.toString(Response.GetStatus())).Observe(Completedtime); }}
Configuring the Controller

Mainly to test the effectiveness of the Interceptor.

@RestController Public classHomeController {Private Static FinalLogger Logger = loggerfactory.GetLogger(HomeController.class);@RequestMapping("/endpointa") Public void Handlera()throwsinterruptedexception {logger.Info("/endpointa"); Thread.Sleep(Randomutils.Nextlong(0, -)); }@RequestMapping("/ENDPOINTB") Public void Handlerb()throwsinterruptedexception {logger.Info("/ENDPOINTB"); Thread.Sleep(Randomutils.Nextlong(0, -)); }}

The above are configured to start the project after completion.

Configure Prometheus

VI prometheus.yml

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

After saving, restart Prometheus.

Access to the Http://ip/targets service state for up instructions is configured successfully, and many tutorials refer to the need to configure Spring.metrics.servo.enabled=false, Otherwise in the Prometheus console of the Targets tab, will always show this endpoint as down state, but it seems that there is no configuration is OK.

Visit Http://ip/graph Test the effect

Configure Grafana

Reference links

https://blog.52itstyle.com/archives/1984/

https://blog.52itstyle.com/archives/2084/

https://raymondhlee.wordpress.com/2016/09/24/monitoring-spring-boot-applications-with-prometheus/

https://raymondhlee.wordpress.com/2016/10/03/monitoring-spring-boot-applications-with-prometheus-part-2/

Springboot of Grafana+prometheus system monitoring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.