In Project Reactor 3.2, reactive types Flux and Mono obtained a metrics() operator. This reports operational metrics regarding the stream when called. The metrics() operator behaves similarly to the log() operator. It cooperates with the name() operator to build a target metric name and add a tag. For example, the following code demonstrates how to add metrics to an outgoing SSE stream:
@GetMapping( path = "/temperature-stream", produces = MediaType.TEXTEVENTSTREAMVALUE) public Flux<Temperature> events() { return temperatureSensor.temperatureStream() // (1) .name("temperature.stream") // (2) .metrics(); // (3) }
Here, the temperatureSensor.temperatureStream() returns Flux<Temperature> (1), while the name("temperature.stream") method adds a name for a monitoring point (2). The metrics() method (3) registers a new metric into the MeterRegistry instance.
As a result, the Reactor library registers the following counters—reactor.subscribed, reactor.requested and the following timers—reactor.flow.duration, reactor.onNext.delay, each of which has a tag (dimension) called flow with a temperature.stream value. These metrics alone allow us to track the number of stream instantiations, the number of requested elements, the maximum and total time for stream existence as well as onNext delay.