Rework MaxMind circuit breaker

This commit is contained in:
Colin McDonald 2016-07-16 22:57:09 -04:00
parent 5f322824ac
commit eb03636a6b
1 changed files with 10 additions and 4 deletions

View File

@ -8,12 +8,14 @@ import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.json.JsonObject;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import net.frozenorb.apiv3.APIv3;
import net.frozenorb.apiv3.maxmind.MaxMindResult;
import java.util.Base64;
@UtilityClass
@Slf4j
public class MaxMindUtils {
private static final String maxMindUserId = APIv3.getConfig().getProperty("maxMind.userId");
@ -28,14 +30,18 @@ public class MaxMindUtils {
breaker = CircuitBreaker.create("maxmind-circuit-breaker", APIv3.getVertxInstance(),
new CircuitBreakerOptions()
.setMaxFailures(5)
.setTimeout(1000) // 1 second
.setTimeout(5000) // 5 secondS
.setFallbackOnFailure(true)
.setResetTimeout(120_000) // 2 minutes
);
breaker.fallback((ignored) -> null);
breaker.openHandler((ignored) -> log.info("MaxMind circuit breaker is now open."));
breaker.halfOpenHandler((ignored) -> log.info("MaxMind circuit breaker is now half-open."));
breaker.closeHandler((ignored) -> log.info("MaxMind circuit breaker is now closed."));
}
public static void getInsights(String ip, SingleResultCallback<MaxMindResult> callback) {
breaker.executeWithFallback((future) -> {
breaker.execute((future) -> {
String authHeader = "Basic " + Base64.getEncoder().encodeToString((maxMindUserId + ":" + maxMindLicenseKey).getBytes(Charsets.UTF_8));
httpsClient.get(443, "geoip.maxmind.com", "/geoip/v2.1/insights/" + ip, (response) -> {
@ -52,14 +58,14 @@ public class MaxMindUtils {
response.exceptionHandler((error) -> {
// we have to check !failed because the circuit breaker's timeout will mark us as failed already
if (!future.failed()) {
if (future.isComplete()) {
future.fail(error);
}
});
})
.putHeader("Authorization", authHeader)
.end();
}, (ignored) -> null).setHandler((result) -> { // The (ignored) -> null section is our fallback, which just returns null (when the breaker is open)
}).setHandler((result) -> {
if (result.failed()) {
callback.onResult(null, result.cause());
} else {