Java – How to use Micrometer timers with webflux endpoints

How to use Micrometer timers with webflux endpoints… here is a solution to the problem.

How to use Micrometer timers with webflux endpoints

Is there any easy way to use the Micrometer timer with Webflux Controller?

@Timed seems to only work for non-active methods. For Reactive, it records very low time values.

I found a similar problem: How to use Micrometer Timer to record duration of async method (returns Mono or Flux) But for such a common question, the answer is too complicated

Any ideas?

Solution

If you want to measure the time of web-flux methods/calls, you can easily use metrics directly from Flux/Mono (plus configure your project to export metrics, such as Graphite).

An example looks like

Flux<String> dataStream = Flux.just("AA", "BB", "CC", "DD");
dataStream.name("my-test-name").tag("key1", "value1").metrics().subscribe(p ->
   {
      System.out.println("Hello " + p);
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         e.printStackTrace();
   }
});

Then in my case, the indicator in Graphite, for example, is in application-name.magdalena reactor.flow.duration.exception.flow.my-test-name.status.completed.type.Flux.p50 top >
p50 – is the latency of half the requests (or 98% pf requests and so on). Thanks to their artificial delay in this example, you can observe that their values are close to 4000 (1s x 4 elements processed).

Graphite’s configuration in application.yml:

management:
    metrics:
        export:
            graphite:
                enabled: true
                host: graphite-lhr10.something.com
                port: 2003
                protocol: plaintext

@Timed Comments don’t work for me either.

Related Problems and Solutions