Java Code Examples for io.vertx.circuitbreaker.CircuitBreaker#create()

The following examples show how to use io.vertx.circuitbreaker.CircuitBreaker#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseMicroserviceVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
  // init service discovery instance
  discovery = ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions().setBackendConfiguration(config()));

  // init circuit breaker instance
  JsonObject cbOptions = config().getJsonObject("circuit-breaker") != null ?
    config().getJsonObject("circuit-breaker") : new JsonObject();
  circuitBreaker = CircuitBreaker.create(cbOptions.getString("name", "circuit-breaker"), vertx,
    new CircuitBreakerOptions()
      .setMaxFailures(cbOptions.getInteger("max-failures", 5))
      .setTimeout(cbOptions.getLong("timeout", 10000L))
      .setFallbackOnFailure(true)
      .setResetTimeout(cbOptions.getLong("reset-timeout", 30000L))
  );
}
 
Example 2
Source File: PokemonHandler.java    From vertx-in-production with MIT License 6 votes vote down vote up
public PokemonHandler(Vertx vertx) {
    WebClientOptions options = new WebClientOptions().setKeepAlive(true).setSsl(true);
    this.webClient = WebClient.create(vertx, options);

    CircuitBreakerOptions circuitBreakerOptions = new CircuitBreakerOptions()
            .setMaxFailures(3)
            .setTimeout(1000)
            .setFallbackOnFailure(true)
            .setResetTimeout(60000);

    this.circuitBreaker = CircuitBreaker.create("pokeapi", vertx, circuitBreakerOptions);
    this.circuitBreaker.openHandler(v -> logger.info("{} circuit breaker is open", "pokeapi"));
    this.circuitBreaker.closeHandler(v -> logger.info("{} circuit breaker is closed", "pokeapi"));
    this.circuitBreaker.halfOpenHandler(v -> logger.info("{} circuit breaker is half open", "pokeapi"));

    this.healthChecks = HealthChecks.create(vertx);
    healthChecks.register("pokeApiHealthcheck", 1000, future -> {
        if (circuitBreaker.state().equals(CircuitBreakerState.CLOSED)) {
            future.complete(Status.OK());
        } else {
            future.complete(Status.KO());
        }
    });
}
 
Example 3
Source File: DashboardExample.java    From vertx-circuit-breaker with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  Vertx vertx = Vertx.vertx();
  CircuitBreakerOptions options = new CircuitBreakerOptions()
    .setFallbackOnFailure(true)
    .setMaxFailures(10)
    .setResetTimeout(5000)
    .setTimeout(1000)
    .setMetricsRollingWindow(10000);

  CircuitBreaker cba = CircuitBreaker.create("A", vertx, options);
  CircuitBreaker cbb = CircuitBreaker.create("B", vertx, options);
  CircuitBreaker cbc = CircuitBreaker.create("C", vertx, options);

  Router router = Router.router(vertx);
  router.get("/metrics").handler(HystrixMetricHandler.create(vertx));


  router.get("/A").handler(rc -> a(rc, cba));
  router.get("/B").handler(rc -> b(rc, cbb));
  router.get("/C").handler(rc -> c(rc, cbc));

  vertx.createHttpServer()
    .requestHandler(router)
    .listen(8080);
}
 
Example 4
Source File: UsageTest.java    From vertx-circuit-breaker with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  vertx = Vertx.vertx();
  items.clear();
  cb = CircuitBreaker.create("circuit-breaker", vertx, new CircuitBreakerOptions()
      .setFallbackOnFailure(true)
      .setTimeout(500)
      .setResetTimeout(1000));

  vertx.eventBus().consumer("ok", message -> message.reply("OK"));

  vertx.eventBus().consumer("fail", message -> message.fail(100, "Bad bad bad"));

  vertx.eventBus().consumer("exception", message -> {
    throw new RuntimeException("RT - Bad bad bad");
  });

  vertx.eventBus().consumer("timeout", message -> vertx.setTimer(2000, x -> message.reply("Too late")));
}
 
Example 5
Source File: CircuitBreakerWithHTTPTest.java    From vertx-circuit-breaker with Apache License 2.0 6 votes vote down vote up
@Test
public void testOk() {
  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions());
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);

  Promise<String> result = Promise.promise();
  breaker.executeAndReport(result, v -> client.get(8080, "localhost", "/",
    ar -> {
      if (ar.succeeded()) {
        HttpClientResponse response = ar.result();
        response.bodyHandler(buffer -> v.complete(buffer.toString()));
      }
    }));

  await().until(() -> result.future().result() != null);
  assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED);
}
 
Example 6
Source File: APITest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithOperationWithCompletionHandler() {
  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions());

  AtomicInteger result = new AtomicInteger();

  breaker.executeWithFallback(fut -> {
    MyAsyncOperations.operation(1, 1, fut);
  }, v -> 0, ar -> result.set(ar.result()));

  await().untilAtomic(result, is(2));
}
 
Example 7
Source File: NumberOfRetryTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithRetrySetToOne() {
  CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
    new CircuitBreakerOptions().setMaxFailures(5).setMaxRetries(1));
  AtomicInteger counter = new AtomicInteger();

  breaker.execute(future -> {
    counter.incrementAndGet();
    future.fail("FAILED");
  }).onComplete(ar -> {

  });

  await().untilAtomic(counter, is(2));
}
 
Example 8
Source File: NumberOfRetryTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithRetrySetToZero() {
  CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
    new CircuitBreakerOptions().setMaxFailures(5).setMaxRetries(0));
  AtomicInteger counter = new AtomicInteger();

  breaker.execute(future -> {
    counter.incrementAndGet();
    future.fail("FAILED");
  }).onComplete(ar -> {

  });

  await().untilAtomic(counter, is(1));
}
 
Example 9
Source File: FailoverInvoker.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    circuitBreaker = CircuitBreaker.create("cb-" + options.hashCode(),
            vertx,
            new CircuitBreakerOptions()
                    .setMaxRetries(options.getMaxAttempts()) // number of failure before opening the circuit
                    .setTimeout(options.getRetryTimeout()) // consider a failure if the operation does not succeed in time
                    .setResetTimeout(10000L) // time spent in open state before attempting to re-try
                    .setNotificationAddress(null));
}
 
Example 10
Source File: APITest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithOperationWithFuture() {
  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions()
      .setFallbackOnFailure(true));

  AtomicInteger result = new AtomicInteger();
  Promise<Integer> operationResult = Promise.promise();
  operationResult.future().onComplete(ar -> {
    result.set(ar.result());
  });

  breaker.executeAndReport(operationResult, future -> MyAsyncOperations.operation(future, 1, 1));

  await().untilAtomic(result, is(2));
}
 
Example 11
Source File: APITest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithFailingOperationWithCompletionHandler() {
  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions()
    .setFallbackOnFailure(true));

  AtomicInteger result = new AtomicInteger();

  breaker.executeWithFallback(fut -> {
    MyAsyncOperations.fail(fut);
  }, v -> -1, ar -> result.set(ar.result()));

  await().untilAtomic(result, is(-1));
}
 
Example 12
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testLatencyComputation(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx);
  Async async = tc.async();


  int count = 1000;

  // Future chain
  Future<Void> fut = breaker.execute(commandThatWorks());
  for (int i = 1; i < count; i++) {
    Future<Void> newFut = breaker.execute(commandThatWorks());
    fut = fut.compose(v -> newFut); // Chain futures
  }

  fut
    .onComplete(ar -> {
      assertThat(ar).succeeded();
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("failures", 0)
        .contains("totalErrorCount", 0)
        .contains("totalSuccessCount", count)
        .contains("totalTimeoutCount", 0)
        .contains("totalExceptionCount", 0)
        .contains("totalFailureCount", 0)
        .contains("totalOperationCount", count)
        .contains("totalSuccessPercentage", 100)
        .contains("totalErrorPercentage", 0);
      assertThat(metrics().getInteger("totalLatencyMean")).isNotZero();
      async.complete();
    });
}
 
Example 13
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testWithTimeoutCommands(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx, new CircuitBreakerOptions().setTimeout(100));
  Async async = tc.async();

  Future<Void> command1 = breaker.execute(commandThatFails());
  Future<Void> command2 = breaker.execute(commandThatWorks());
  Future<Void> command3 = breaker.execute(commandThatWorks());
  Future<Void> command4 = breaker.execute(commandThatFails());
  Future<Void> command5 = breaker.execute(commandThatTimeout(100));

  CompositeFuture.join(command1, command2, command3, command4, command5)
    .onComplete(ar -> {
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("totalErrorCount", 3) // Failure + Timeout + Exception
        .contains("totalSuccessCount", 2)
        .contains("totalTimeoutCount", 1)
        .contains("totalExceptionCount", 0)
        .contains("totalFailureCount", 2)
        .contains("totalOperationCount", 5)
        .contains("totalSuccessPercentage", (2.0 / 5 * 100))
        .contains("totalErrorPercentage", (3.0 / 5 * 100));
      async.complete();
    });
}
 
Example 14
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testWithCrashingCommands(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx);
  Async async = tc.async();

  Future<Void> command1 = breaker.execute(commandThatFails());
  Future<Void> command2 = breaker.execute(commandThatWorks());
  Future<Void> command3 = breaker.execute(commandThatWorks());
  Future<Void> command4 = breaker.execute(commandThatFails());
  Future<Void> command5 = breaker.execute(commandThatCrashes());

  CompositeFuture.join(command1, command2, command3, command4, command5)
    .onComplete(ar -> {
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("totalErrorCount", 3) // Failure + Timeout + Exception
        .contains("totalSuccessCount", 2)
        .contains("totalTimeoutCount", 0)
        .contains("totalExceptionCount", 1)
        .contains("totalFailureCount", 2)
        .contains("totalOperationCount", 5)
        .contains("totalSuccessPercentage", (2.0 / 5 * 100))
        .contains("totalErrorPercentage", (3.0 / 5 * 100));
      async.complete();
    });
}
 
Example 15
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testWithFailedCommands(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx);
  Async async = tc.async();

  Future<Void> command1 = breaker.execute(commandThatFails());
  Future<Void> command2 = breaker.execute(commandThatWorks());
  Future<Void> command3 = breaker.execute(commandThatWorks());
  Future<Void> command4 = breaker.execute(commandThatFails());

  CompositeFuture.join(command1, command2, command3, command4)
    .onComplete(ar -> {
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("totalErrorCount", 2) // Failure + Timeout + Exception
        .contains("totalSuccessCount", 2)
        .contains("totalTimeoutCount", 0)
        .contains("totalExceptionCount", 0)
        .contains("totalFailureCount", 2)
        .contains("totalOperationCount", 4)
        .contains("totalSuccessPercentage", 50)
        .contains("totalErrorPercentage", 50);
      async.complete();
    });
}
 
Example 16
Source File: CircuitBreakerMetricsTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
@Repeat(10)
public void testWithSuccessfulCommands(TestContext tc) {
  breaker = CircuitBreaker.create("some-circuit-breaker", vertx);
  Async async = tc.async();


  Future<Void> command1 = breaker.execute(commandThatWorks());
  Future<Void> command2 = breaker.execute(commandThatWorks());
  Future<Void> command3 = breaker.execute(commandThatWorks());

  CompositeFuture.all(command1, command2, command3)
    .onComplete(ar -> {
      assertThat(ar).succeeded();
      assertThat(metrics())
        .contains("name", "some-circuit-breaker")
        .contains("state", CircuitBreakerState.CLOSED.name())
        .contains("failures", 0)
        .contains("totalErrorCount", 0)
        .contains("totalSuccessCount", 3)
        .contains("totalTimeoutCount", 0)
        .contains("totalExceptionCount", 0)
        .contains("totalFailureCount", 0)
        .contains("totalOperationCount", 3)
        .contains("totalSuccessPercentage", 100)
        .contains("totalErrorPercentage", 0);

      async.complete();
    });
}
 
Example 17
Source File: APITest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithFailingOperationWithHandler() {
  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions()
      .setFallbackOnFailure(true));

  AtomicInteger result = new AtomicInteger();

  breaker.<Integer>executeWithFallback(fut -> {
    MyAsyncOperations.fail(fut);
  }, v -> -1)
      .onComplete(ar -> result.set(ar.result()));

  await().untilAtomic(result, is(-1));
}
 
Example 18
Source File: APITest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithFailingOperationWithFuture() {
  breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions()
      .setFallbackOnFailure(true));

  AtomicInteger result = new AtomicInteger();

  Promise<Integer> operationResult = Promise.promise();
  operationResult.future().onComplete(ar -> result.set(ar.result()));

  breaker.executeAndReportWithFallback(operationResult, MyAsyncOperations::fail, t -> -1);

  await().untilAtomic(result, is(-1));
}
 
Example 19
Source File: CircuitBreakerExamples.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
public void example3(Vertx vertx) {
  CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
      new CircuitBreakerOptions().setMaxFailures(5).setTimeout(2000)
  );

  // ---
  // Store the circuit breaker in a field and access it as follows
  // ---

  breaker.executeWithFallback(
      promise -> {
        vertx.createHttpClient().get(8080, "localhost", "/", ar -> {
          if (ar.succeeded()) {
            HttpClientResponse response = ar.result();
            if (response.statusCode() != 200) {
              promise.fail("HTTP error");
            } else {
              response
                .exceptionHandler(promise::fail)
                .bodyHandler(buffer -> {
                  promise.complete(buffer.toString());
                });
            }
          } else {
            promise.fail("Connect error");
          }
        });
      }, v -> {
        // Executed when the circuit is opened
        return "Hello";
      })
      .onComplete(ar -> {
        // Do something with the result
      });
}
 
Example 20
Source File: CircuitBreakerExamples.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
public void example2(Vertx vertx) {
  CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
      new CircuitBreakerOptions().setMaxFailures(5).setTimeout(2000)
  );

  // ---
  // Store the circuit breaker in a field and access it as follows
  // ---

  breaker.<String>execute(promise -> {
    vertx.createHttpClient().get(8080, "localhost", "/", ar -> {
      if (ar.succeeded()) {
        HttpClientResponse response = ar.result();
        if (response.statusCode() != 200) {
          promise.fail("HTTP error");
        } else {
          response
            .exceptionHandler(promise::fail)
            .bodyHandler(buffer -> {
              promise.complete(buffer.toString());
            });
        }
      } else {
        promise.fail("Request error");
      }
    });
  }).onComplete(ar -> {
    // Do something with the result
  });
}