io.vertx.circuitbreaker.CircuitBreaker Java Examples
The following examples show how to use
io.vertx.circuitbreaker.CircuitBreaker.
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: PluginManagerVerticle.java From dfx with Apache License 2.0 | 6 votes |
private Router buildRouter(DfxConfig config, Map<String, Accessible> accessibleMap) { Router router = Router.router(vertx); try { addCorsHandler(router, config.getCors()); }catch (Exception e) { logger.error("Adding CORS handler failed, cause: {}", e); vertx.close(); System.exit(-1); } config.getMappings().forEach((key, value) -> { CircuitBreaker circuitBreaker = CircuitBreaker.create(key, vertx , config.getCircuitBreakerOptions()); if (accessibleMap.get(value) != null) { router.route(key).handler(new AccessibleHandler(key, accessibleMap.get(value) , circuitBreaker, vertx)); } } ); return router; }
Example #2
Source File: BaseMicroserviceVerticle.java From vertx-blueprint-microservice with Apache License 2.0 | 6 votes |
@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 #3
Source File: RetryPolicyTest.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
/** * Helper method to run retry policy tests */ private void runRetryPolicyTest(Function<Integer, Long> retryPolicy) { CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx, new CircuitBreakerOptions().setMaxFailures(5).setMaxRetries(5)); AtomicInteger counter = new AtomicInteger(); AtomicInteger retryPolicyCounter = new AtomicInteger(); breaker.retryPolicy(retry -> { retryPolicyCounter.incrementAndGet(); return retryPolicy.apply(retry); }); breaker.execute(future -> { counter.incrementAndGet(); future.fail("FAILED"); }).onComplete(ar -> { }); await().untilAtomic(counter, is(6)); await().untilAtomic(retryPolicyCounter, is(5)); }
Example #4
Source File: CircuitBreakerWithHTTPTest.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
@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 #5
Source File: CircuitBreakerMetricsTest.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
@Test @Repeat(100) public void testEviction(TestContext tc) { breaker = CircuitBreaker.create("some-circuit-breaker", vertx, new CircuitBreakerOptions().setMetricsRollingWindow(10)); Async async = tc.async(); int count = 1000; List<Future> list = new ArrayList<>(); for (int i = 0; i < count; i++) { list.add(breaker.execute(commandThatWorks())); } CompositeFuture.all(list) .onComplete(ar -> { assertThat(ar).succeeded(); assertThat(metrics().getInteger("totalOperationCount")).isEqualTo(1000); assertThat(metrics().getInteger("rollingOperationCount")).isLessThanOrEqualTo(1000); async.complete(); }); }
Example #6
Source File: UsageTest.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
@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 #7
Source File: DashboardExample.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
private static void c(RoutingContext rc, CircuitBreaker cb) { int choice = random.nextInt(10); if (choice < 5) { cb.executeWithFallback( commandThatWorks(rc.vertx()), (t) -> "OK (fallback)") .onComplete(s -> rc.response().end(s.result())); } else if (choice < 7) { cb.executeWithFallback( commandThatTimeout(rc.vertx(), 15000), (t) -> "OK (fallback)") .onComplete(s -> rc.response().end(s.result())); } else { cb.executeWithFallback( commandThatFails(rc.vertx()), (t) -> "OK (fallback)") .onComplete(s -> rc.response().end(s.result())); } }
Example #8
Source File: DashboardExample.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
private static void b(RoutingContext rc, CircuitBreaker cb) { int choice = random.nextInt(10); if (choice < 5) { cb.executeWithFallback( commandThatWorks(rc.vertx()), (t) -> "OK (fallback)") .onComplete(s -> rc.response().end(s.result())); } else if (choice < 7) { cb.executeWithFallback( commandThatCrashes(rc.vertx()), (t) -> "OK (fallback)") .onComplete(s -> rc.response().end(s.result())); } else { cb.executeWithFallback( commandThatFails(rc.vertx()), (t) -> "OK (fallback)") .onComplete(s -> rc.response().end(s.result())); } }
Example #9
Source File: DashboardExample.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
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 #10
Source File: CircuitBreakerImpl.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
/** * A version of reset that can force the the state to `close` even if the circuit breaker is open. This is an * internal API. * * @param force whether or not we force the state and allow an illegal transition * @return the current circuit breaker. */ public synchronized CircuitBreaker reset(boolean force) { rollingFailures.reset(); if (state == CircuitBreakerState.CLOSED) { // Do nothing else. return this; } if (!force && state == CircuitBreakerState.OPEN) { // Resetting the circuit breaker while we are in the open state is an illegal transition return this; } state = CircuitBreakerState.CLOSED; closeHandler.handle(null); sendUpdateOnEventBus(); return this; }
Example #11
Source File: CircuitBreakerExamples.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
public void example8(Vertx vertx) { CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx, new CircuitBreakerOptions().setMaxFailures(5).setMaxRetries(5).setTimeout(2000) ).openHandler(v -> { System.out.println("Circuit opened"); }).closeHandler(v -> { System.out.println("Circuit closed"); }).retryPolicy(retryCount -> retryCount * 100L); breaker.execute( promise -> { vertx.createHttpClient().get(8080, "localhost", "/", ar -> { if (ar.succeeded()) { HttpClientResponse response = ar.result(); if (response.statusCode() != 200) { promise.fail("HTTP error"); } else { // Do something with the response promise.complete(); } } else { promise.fail("Connect error"); } }); }); }
Example #12
Source File: PokemonHandler.java From vertx-in-production with MIT License | 6 votes |
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 #13
Source File: Utils.java From dfx with Apache License 2.0 | 6 votes |
public static void withCircuitBreaker(Vertx vertx, CircuitBreaker circuitBreaker , Accessible accessible, Map params, Handler<Map> successHandler, Handler<Throwable> failureHandler) { circuitBreaker.execute(future -> vertx.executeBlocking(f -> { try { f.complete(accessible.invoke(params)); } catch (Throwable throwable) { f.fail(throwable); } } , result -> { if (result.succeeded()) { future.complete(result.result()); } else { future.fail(result.cause()); } }) ).setHandler(result -> { if (result.succeeded()) { successHandler.handle((Map) result.result()); } else { logger.error("CB[{}] execution failed, cause: ", circuitBreaker.name(), result.cause()); failureHandler.handle(result.cause()); } }); }
Example #14
Source File: CircuitBreakerExamples.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
public void example7(Vertx vertx) { // Create the circuit breaker as usual. CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx); CircuitBreaker breaker2 = CircuitBreaker.create("my-second-circuit-breaker", vertx); // Create a Vert.x Web router Router router = Router.router(vertx); // Register the metric handler router.get("/hystrix-metrics").handler(HystrixMetricHandler.create(vertx)); // Create the HTTP server using the router to dispatch the requests vertx.createHttpServer() .requestHandler(router) .listen(8080); }
Example #15
Source File: CircuitBreakerExamples.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
public void example1(Vertx vertx) { CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx, new CircuitBreakerOptions() .setMaxFailures(5) // number of failure before opening the circuit .setTimeout(2000) // consider a failure if the operation does not succeed in time .setFallbackOnFailure(true) // do we call the fallback on failure .setResetTimeout(10000) // time spent in open state before attempting to re-try ); // --- // Store the circuit breaker in a field and access it as follows // --- breaker.execute(promise -> { // some code executing with the breaker // the code reports failures or success on the given promise. // if this promise is marked as failed, the breaker increased the // number of failures }).onComplete(ar -> { // Get the operation result. }); }
Example #16
Source File: CircuitBreakerExamples.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
public void example5(Vertx vertx) { CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx, new CircuitBreakerOptions().setMaxFailures(5).setTimeout(2000) ).openHandler(v -> { System.out.println("Circuit opened"); }).closeHandler(v -> { System.out.println("Circuit closed"); }); breaker.execute( promise -> { vertx.createHttpClient().get(8080, "localhost", "/", ar -> { if (ar.succeeded()) { HttpClientResponse response = ar.result(); if (response.statusCode() != 200) { promise.fail("HTTP error"); } else { // Do something with the response promise.complete(); } } else { promise.fail("Connect error"); } }); }); }
Example #17
Source File: APITest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
/** * Reproducer of https://github.com/vert-x3/vertx-circuit-breaker/issues/9 */ @Test public void testWhenOptionsAreNull() { CircuitBreaker cb = CircuitBreaker.create("name", vertx, null); assertThat(cb).isNotNull(); assertThat(cb.name()).isEqualTo("name"); assertThat(cb.state()).isEqualTo(CircuitBreakerState.CLOSED); }
Example #18
Source File: CircuitBreakerMetricsTest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@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 #19
Source File: CircuitBreakerWithHTTPTest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@Test public void testTimeout() { CircuitBreakerOptions options = new CircuitBreakerOptions().setTimeout(100).setMaxFailures(2); breaker = CircuitBreaker.create("test", vertx, options); assertThat(breaker.state()).isEqualTo(CircuitBreakerState.CLOSED); AtomicInteger count = new AtomicInteger(); for (int i = 0; i < options.getMaxFailures(); i++) { breaker.execute(future -> client.get(8080, "localhost", "/long", response -> { count.incrementAndGet(); future.complete(); })); } await().untilAtomic(count, is(options.getMaxFailures())); assertThat(breaker.state()).isEqualTo(CircuitBreakerState.OPEN); Promise<String> result = Promise.promise(); breaker.executeAndReportWithFallback(result, future -> client.get(8080, "localhost", "/long", response -> { System.out.println("Got response"); future.complete(); }), v -> "fallback"); await().until(() -> result.future().result().equals("fallback")); assertThat(breaker.state()).isEqualTo(CircuitBreakerState.OPEN); }
Example #20
Source File: NumberOfRetryTest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@Test public void testWithoutRetry() { CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx, new CircuitBreakerOptions().setMaxFailures(5)); AtomicInteger counter = new AtomicInteger(); breaker.execute(future -> { counter.incrementAndGet(); future.fail("FAILED"); }).onComplete(ar -> { }); await().untilAtomic(counter, is(1)); }
Example #21
Source File: NumberOfRetryTest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@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 #22
Source File: NumberOfRetryTest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@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 #23
Source File: NumberOfRetryTest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@Test public void testWithRetrySetToFive() { CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx, new CircuitBreakerOptions().setMaxFailures(5).setMaxRetries(5)); AtomicInteger counter = new AtomicInteger(); breaker.execute(future -> { counter.incrementAndGet(); future.fail("FAILED"); }).onComplete(ar -> { }); await().untilAtomic(counter, is(6)); }
Example #24
Source File: CircuitBreakerMetricsTest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@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 #25
Source File: APITest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@Test public void testWithOperationWithHandler() { breaker = CircuitBreaker.create("test", vertx, new CircuitBreakerOptions()); AtomicInteger result = new AtomicInteger(); breaker.<Integer>executeWithFallback(fut -> { MyAsyncOperations.operation(1, 1, fut); }, v -> 0) .onComplete(ar -> result.set(ar.result())); await().untilAtomic(result, is(2)); }
Example #26
Source File: APITest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@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 #27
Source File: APITest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@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 #28
Source File: APITest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@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 #29
Source File: APITest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@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 #30
Source File: APITest.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
@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)); }