Spring获取Http响应时间和状态原理

spring-actuate是spring的监控模块,默认开启很监控下,其中就有个http的响应时间和状态。
在maven的pom中引入

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-actuatorartifactId>
    <version>1.5.3.RELEASEversion>
dependency>

启动项目,访问 http://localhost:prot/metrics 可以看到的结果中

  • “counter.status.200.metrics”:24 表示/metrics接口响应200状态24次
  • “gauge.response.metrics”:2.0 表示/metrics接口响应时间为2ms
    之后通过字符串替换,将key改成自己想要的格式

那么actuate又是如何获取到接口的响应时间和状态?

在sprint-actuate里有个MetricsFilter类,继承了OncePerRequestFilter,从名字上可以看出,这个拦截器会在每次请求执行一次,在请求处理前记录开始时间,请求处理后记录结束时间和响应状态

final class MetricsFilter extends OncePerRequestFilter {
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        StopWatch stopWatch = this.createStopWatchIfNecessary(request);
        String path = (new UrlPathHelper()).getPathWithinApplication(request);
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();

        try {
            chain.doFilter(request, response);
            status = this.getStatus(response);
        } finally {
            if (!request.isAsyncStarted()) {
                if (response.isCommitted()) {
                    status = this.getStatus(response);
                }

                stopWatch.stop();
                request.removeAttribute(ATTRIBUTE_STOP_WATCH);
                this.recordMetrics(request, path, status, stopWatch.getTotalTimeMillis());
            }

        }

    }

    ...
}

最后,处理时长会存为Gauge类型,响应状态次数会存为Counter类型,Gauge存在实现了GaugeService接口的类中,Counter存在实现了CounterService接口的类中。这些类会在MetricsFilter实例化的时候传入

MetricsFilter(CounterService counterService, GaugeService gaugeService, MetricFilterProperties properties) {
        this.counterService = counterService;
        this.gaugeService = gaugeService;
        this.properties = properties;
    }

http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#production-ready 官方文档

你可能感兴趣的:(spring,maven,监控,响应时间,次数)