Skip to content

Commit

Permalink
Add custom metric for rate limit remaining count
Browse files Browse the repository at this point in the history
Now that we have Micrometer set up, we can create an additional,
custom metric for our application. In this case, we'd like to
track the remaining calls to the rate-limited API we're using.
  • Loading branch information
bclozel authored and snicoll committed May 24, 2019
1 parent 58f3ed7 commit c15d4d9
Showing 1 changed file with 20 additions and 2 deletions.
@@ -1,18 +1,23 @@
package io.spring.sample.dashboard.stats;

import java.util.concurrent.atomic.AtomicInteger;

import io.micrometer.core.instrument.MeterRegistry;
import io.spring.sample.dashboard.stats.support.ReverseLookupDescriptor;
import reactor.core.publisher.Mono;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;

@Component
public class ReverseLookupClient {

private final WebClient client;

public ReverseLookupClient(WebClient.Builder builder) {
this.client = builder.build();
public ReverseLookupClient(WebClient.Builder builder, MeterRegistry registry) {
this.client = builder.filter(rateLimitRemainingMetric(registry)).build();
}

public Mono<ReverseLookupDescriptor> freeReverseLookup(String ip) {
Expand All @@ -24,4 +29,17 @@ public Mono<ReverseLookupDescriptor> payingReverseLookup(String ip) {
return this.client.get().uri("http://localhost:8081/reverse-lookup/costly/{ip}", ip)
.retrieve().bodyToMono(ReverseLookupDescriptor.class);
}

private ExchangeFilterFunction rateLimitRemainingMetric(MeterRegistry registry) {
AtomicInteger rateLimitRemaining = registry
.gauge("reverselookup.ratelimit.remaining", new AtomicInteger(0));
return (request, next) -> next.exchange(request)
.doOnNext(response -> {
String remaining = response.headers().asHttpHeaders()
.getFirst("X-RateLimit-Remaining");
if (StringUtils.hasText(remaining)) {
rateLimitRemaining.set(Integer.valueOf(remaining));
}
});
}
}

0 comments on commit c15d4d9

Please sign in to comment.