How to calculate total execution time and set in r

2020-03-29 09:07发布

问题:

I don't know my approach is correct or not? Also, please let me know if there is any other work-around to achieve this.

Is it possible using WebFilter?

package request.middlewares;

import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Component
public class ResponseTimeCalculator implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        // is it possible here?
        exchange.getResponse().getHeaders().add("X-Runtime", "10ms");
        return chain.filter(exchange);
    }
}

回答1:

If you're using Spring Boot, you should use spring-boot-starter-actuator for that.

If you're not using Spring Boot, you should still take a look at Micrometer, which instruments Spring WebFlux to gather that kind of data.

Note that there are many pitfalls to your approach:

  • the handler chain might return but the actual response handling/writing might not be done yet
  • using a simple timer won't take into account GC pauses
  • looking at measures samples is not really important, percentiles give you much more

In any case, you can take a look at Spring Boot's MetricsWebFilter (here) to check how this is achieved with Micrometer.