io.vertx.circuitbreaker.CircuitBreakerOptions Java Examples
The following examples show how to use
io.vertx.circuitbreaker.CircuitBreakerOptions.
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: CircuitBreaker.java From prebid-server-java with Apache License 2.0 | 6 votes |
public CircuitBreaker(String name, Vertx vertx, int openingThreshold, long openingIntervalMs, long closingIntervalMs, Clock clock) { breaker = io.vertx.circuitbreaker.CircuitBreaker.create( Objects.requireNonNull(name), Objects.requireNonNull(vertx), new CircuitBreakerOptions() .setMaxFailures(openingThreshold) .setResetTimeout(closingIntervalMs)); this.vertx = vertx; this.openingIntervalMs = openingIntervalMs; this.clock = Objects.requireNonNull(clock); }
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 |
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 #8
Source File: CircuitBreakerImpl.java From vertx-circuit-breaker with Apache License 2.0 | 6 votes |
public CircuitBreakerImpl(String name, Vertx vertx, CircuitBreakerOptions options) { Objects.requireNonNull(name); Objects.requireNonNull(vertx); this.vertx = vertx; this.name = name; if (options == null) { this.options = new CircuitBreakerOptions(); } else { this.options = new CircuitBreakerOptions(options); } this.metrics = new CircuitBreakerMetrics(vertx, this, options); this.rollingFailures = new RollingCounter(options.getFailuresRollingWindow() / 1000, TimeUnit.SECONDS); sendUpdateOnEventBus(); if (this.options.getNotificationPeriod() > 0) { this.periodicUpdateTask = vertx.setPeriodic(this.options.getNotificationPeriod(), l -> sendUpdateOnEventBus()); } else { this.periodicUpdateTask = -1; } }
Example #9
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 #10
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 #11
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 #12
Source File: CurrencyServiceProxy.java From vertx-kubernetes-workshop with Apache License 2.0 | 6 votes |
@Override public void start() throws Exception { Router router = Router.router(vertx); router.get().handler(this::convertPortfolioToEuro); router.post().handler(BodyHandler.create()); router.post().handler(this::delegateWithCircuitBreaker); circuit = CircuitBreaker.create("circuit-breaker", vertx, new CircuitBreakerOptions() .setFallbackOnFailure(true) .setMaxFailures(3) .setResetTimeout(5000) .setTimeout(1000) ); discovery = ServiceDiscovery.create(vertx); vertx.createHttpServer() .requestHandler(router::accept) .listen(8080); }
Example #13
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 #14
Source File: CurrencyServiceProxy.java From vertx-kubernetes-workshop with Apache License 2.0 | 6 votes |
@Override public void start() throws Exception { Router router = Router.router(vertx); router.get().handler(this::convertPortfolioToEuro); router.post().handler(BodyHandler.create()); router.post().handler(this::delegateWithCircuitBreaker); circuit = CircuitBreaker.create("circuit-breaker", vertx, new CircuitBreakerOptions() .setFallbackOnFailure(true) .setMaxFailures(3) .setResetTimeout(5000) .setTimeout(1000) ); discovery = ServiceDiscovery.create(vertx); vertx.createHttpServer() .requestHandler(router::accept) .listen(8080); }
Example #15
Source File: FailoverInvoker.java From gravitee-gateway with Apache License 2.0 | 5 votes |
@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 #16
Source File: CircuitBreakerExamples.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
public void example6(Vertx vertx) { CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx, new CircuitBreakerOptions().setMaxFailures(5).setTimeout(2000) ); Promise<String> userPromise = Promise.promise(); userPromise.future().onComplete(ar -> { // Do something with the result }); breaker.executeAndReportWithFallback( userPromise, 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"; }); }
Example #17
Source File: BaseMicroserviceRxVerticle.java From vertx-blueprint-microservice with Apache License 2.0 | 5 votes |
@Override public void start() throws Exception { discovery = ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions().setBackendConfiguration(config())); 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("maxFailures", 5)) .setTimeout(cbOptions.getLong("timeout", 10000L)) .setFallbackOnFailure(true) .setResetTimeout(cbOptions.getLong("resetTimeout", 30000L)) ); }
Example #18
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)); }
Example #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
Source File: CircuitBreakerExamples.java From vertx-circuit-breaker with Apache License 2.0 | 5 votes |
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 }); }