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

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>1.5.3.RELEASE</version>
</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 官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李昂的数字之旅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值