Java Code Examples for org.eclipse.microprofile.faulttolerance.CircuitBreaker

The following examples show how to use org.eclipse.microprofile.faulttolerance.CircuitBreaker. These examples are extracted from open source projects. 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
@Deployment
public static WebArchive create() {
    ConfigAnnotationAsset config = new ConfigAnnotationAsset();
    config.setGlobally(CircuitBreaker.class, "skipOn", TestConfigExceptionA.class.getCanonicalName());
    
    JavaArchive jar = ShrinkWrap
            .create(JavaArchive.class, "ftCircuitBreakerSkipOnConfig.jar")
            .addPackage(CircuitBreakerConfigTest.class.getPackage())
            .addPackage(Packages.UTILS)
            .addAsManifestResource(config, "microprofile-config.properties")
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
    
    WebArchive war = ShrinkWrap
            .create(WebArchive.class, "ftCircuitBreakerSkipOnConfig.war")
            .addAsLibraries(jar);
    
    return war;
}
 
Example 2
/**
 * Configured to always time out and Retry until CircuitBreaker is triggered on 4th call.
 */
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
@Retry(retryOn = {RuntimeException.class, TimeoutException.class}, maxRetries = 7, maxDuration = 20000)
@Timeout(100) // Scaled via config
public Connection serviceC() {
    Connection conn = null;
    counterForInvokingServiceC++;

    try {
        Thread.sleep(TCKConfig.getConfig().getTimeoutInMillis(5000));
        throw new RuntimeException("Timeout did not interrupt");
    } 
    catch (InterruptedException e) {
        //expected
    }
    return conn;
}
 
Example 3
void registerInterceptorBindings(@Observes BeforeBeanDiscovery bbd, BeanManager bm) {
    LOGGER.info("MicroProfile: Fault Tolerance activated");
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(CircuitBreaker.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Retry.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Timeout.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Asynchronous.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Fallback.class)));
    bbd.addInterceptorBinding(new FTInterceptorBindingAnnotatedType<>(bm.createAnnotatedType(Bulkhead.class)));

    // It seems that fraction deployment module cannot be picked up as a CDI bean archive - see also SWARM-1725
    bbd.addAnnotatedType(bm.createAnnotatedType(FaultToleranceInterceptor.class),
            FaultToleranceInterceptor.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(DefaultFallbackHandlerProvider.class),
            DefaultFallbackHandlerProvider.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(ExecutorProvider.class),
            ExecutorProvider.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(DefaultFaultToleranceOperationProvider.class),
            DefaultFaultToleranceOperationProvider.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(MetricsCollectorFactory.class), MetricsCollectorFactory.class.getName());
    bbd.addAnnotatedType(bm.createAnnotatedType(StrategyCache.class), StrategyCache.class.getName());
}
 
Example 4
@Deployment
public static WebArchive deploy() {
   Asset config = new DisableConfigAsset()
           .enable(Retry.class)
           .enable(CircuitBreaker.class)
           .enable(Timeout.class)
           .enable(Asynchronous.class)
           .enable(Fallback.class)
           .enable(Bulkhead.class)
           .disableGlobally();

    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGlobalEnableClass.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGlobalEnableClass.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 5
@Deployment
public static WebArchive deploy() {
   Asset config = new DisableConfigAsset()
           .enable(DisableAnnotationClient.class, "failAndRetryOnce", Retry.class)
           .enable(DisableAnnotationClient.class, "failWithCircuitBreaker", CircuitBreaker.class)
           .enable(DisableAnnotationClient.class, "failWithTimeout", Timeout.class)
           .enable(DisableAnnotationClient.class, "asyncWaitThenReturn", Asynchronous.class)
           .enable(DisableAnnotationClient.class, "failRetryOnceThenFallback", Fallback.class)
           .enable(DisableAnnotationClient.class, "waitWithBulkhead", Bulkhead.class)
           .disableGlobally();

    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGloballyEnableMethod.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGloballyEnableMethod.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 6
@Deployment
public static WebArchive deploy() {
    Asset config = new DisableConfigAsset()
            .disable(DisableAnnotationClient.class, "failAndRetryOnce", Retry.class)
            .disable(DisableAnnotationClient.class, "failRetryOnceThenFallback", Fallback.class)
            .disable(DisableAnnotationClient.class, "failWithCircuitBreaker", CircuitBreaker.class)
            .disable(DisableAnnotationClient.class, "failWithTimeout", Timeout.class)
            .disable(DisableAnnotationClient.class, "asyncWaitThenReturn", Asynchronous.class)
            .disable(DisableAnnotationClient.class, "waitWithBulkhead", Bulkhead.class);
    
    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableMethods.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableMethods.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 7
@Deployment
public static WebArchive deploy() {
    
    Asset config = new DisableConfigAsset()
            .disable(Retry.class)
            .disable(CircuitBreaker.class)
            .disable(Timeout.class)
            .disable(Asynchronous.class)
            .disable(Fallback.class)
            .disable(Bulkhead.class);
    
    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGlobally.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGlobally.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 8
/**
 * Configured to always time out and Retry until CircuitBreaker is triggered on 4th call. Runs asynchronously.
 */
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
@Retry(retryOn = {TestException.class, TimeoutException.class}, maxRetries = 7, maxDuration = 20000)
@Timeout(100) // Scaled via config
@Asynchronous
public Future<Connection> serviceC() {
    Connection conn = null;
    counterForInvokingServiceC++;

    try {
        Thread.sleep(TCKConfig.getConfig().getTimeoutInMillis(5000));
        throw new RuntimeException("Timeout did not interrupt");
    } 
    catch (InterruptedException e) {
        //expected
    }
    return CompletableFuture.completedFuture(conn);
}
 
Example 9
@CircuitBreaker(successThreshold = 5, requestVolumeThreshold = 4, failureRatio=0.75,
        delay = 1000)
public List<Orders> findAll(Long customerId) {

    possibleFailure();
    return  (List<Orders>) entityManager.createNamedQuery("Orders.findAll")
            .setParameter("customerId", customerId)
            .getResultList();
}
 
Example 10
Source Project: smallrye-fault-tolerance   Source File: PingService.java    License: Apache License 2.0 5 votes vote down vote up
@CircuitBreaker(failOn = { IllegalArgumentException.class })
public String ping() {
    int count = counter.incrementAndGet();

    if (count % 2 == 0) {
        throw new IllegalArgumentException();
    } else {
        throw new IllegalStateException();
    }
}
 
Example 11
@CircuitBreaker(requestVolumeThreshold = THRESHOLD)
public String ping(boolean success) {
    pingCounter.incrementAndGet();
    if (success) {
        return "ok";
    }
    throw new IllegalStateException();
}
 
Example 12
@CircuitBreaker(requestVolumeThreshold = 2, failureRatio = .40, delay = 300)
public String ping(boolean success) {
    pingCounter.incrementAndGet();
    if (success) {
        return "ok";
    }
    throw new IllegalStateException();
}
 
Example 13
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
@Retry(retryOn = {RuntimeException.class}, maxRetries = 2)
public Connection serviceB() {
    Connection conn = null;
    counterForInvokingServiceB++;
    conn = connectionService();
    return conn;
}
 
Example 14
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio=0.5)
public Connection service1RollingWindowOpenAfter4() {
    Connection conn = null;
    counterForInvokingService1++;
    conn = connectionService1();
    
    return conn;
}
 
Example 15
/**
 * Has a CircuitBreaker and Retries on all exceptions except TestException and CircuitBreakerOpenException
 * 
 * @param throwException whether this method should throw a TestException to simulate an application failure
 * @return string "OK"
 */
@CircuitBreaker(requestVolumeThreshold = 4, failureRatio = 0.75, delay = 1000)
@Retry(abortOn = { TestException.class, CircuitBreakerOpenException.class }, maxRetries = 20, delay = 200)
// Scaled via config
public String serviceWithRetryFailOnCbOpen(boolean throwException) {
    if (throwException) {
        throw new TestException();
    }
    else {
        return "OK";
    }
}
 
Example 16
Source Project: smallrye-fault-tolerance   Source File: MyMicroservice.java    License: Apache License 2.0 5 votes vote down vote up
@CircuitBreaker(successThreshold = 3, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 200)
public String sayHelloBreakerHighThreshold() {
    sayHelloBreakerCount5++;
    System.err.printf("sayHelloBreakerHighThreshold, %d\n", sayHelloBreakerCount5);
    // Only two execution succeeds
    if (sayHelloBreakerCount5 < 5 || sayHelloBreakerCount5 > 6) {
        throw new RuntimeException("Connection failed");
    }
    return "sayHelloBreaker#" + sayHelloBreakerCount5;
}
 
Example 17
@Asynchronous
@CircuitBreaker(requestVolumeThreshold = THRESHOLD, failureRatio = 0.5, delay = DELAY, successThreshold = 1)
public Future<String> hello(Result result) throws IOException {
    COUNTER.incrementAndGet();
    switch (result) {
        case FAILURE:
            throw new IOException("Simulated IO error");
        case COMPLETE_EXCEPTIONALLY:
            CompletableFuture<String> future = new CompletableFuture<>();
            future.completeExceptionally(new IOException("Simulated IO error"));
            return future;
        default:
            return completedFuture(OK);
    }
}
 
Example 18
@Asynchronous
@Retry(retryOn = IOException.class)
@CircuitBreaker(failOn = IOException.class, requestVolumeThreshold = 5, successThreshold = 3, delay = 2, delayUnit = ChronoUnit.SECONDS, failureRatio = 0.75)
@Fallback(fallbackMethod = "fallback", applyOn = { IOException.class, CircuitBreakerOpenException.class })
public CompletionStage<String> hello(int counter) throws IOException {
    // 3/4 requests trigger IOException
    if (counter % 4 != 0) {
        throw new IOException("Simulated IOException");
    }

    return completedFuture("Hello" + counter);
}
 
Example 19
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
@Retry(retryOn = {RuntimeException.class}, maxRetries = 2)
public Connection serviceB() {
    Connection conn = null;
    counterForInvokingServiceB++;
    conn = connectionService();
    return conn;
}
 
Example 20
public static FaultToleranceOperation of(Class<?> beanClass, Method method) {
    return new FaultToleranceOperation(beanClass, method,
            isAsync(method, beanClass),
            returnsCompletionStage(method),
            getConfig(Bulkhead.class, beanClass, method, BulkheadConfig::new),
            getConfig(CircuitBreaker.class, beanClass, method, CircuitBreakerConfig::new),
            getConfig(Fallback.class, beanClass, method, FallbackConfig::new),
            getConfig(Retry.class, beanClass, method, RetryConfig::new),
            getConfig(Timeout.class, beanClass, method, TimeoutConfig::new));
}
 
Example 21
/**
 * This method's circuit breaker moves from half-open to closed after 4 consecutive successes,
 * unless successThreshold is configured differently.
 */
@CircuitBreaker(requestVolumeThreshold = 10, successThreshold = 4, delay = 1000)
public void successThresholdMethod(boolean fail) {
    if (fail) {
        throw new TestConfigExceptionA();
    }
}
 
Example 22
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
@Retry(retryOn = {RuntimeException.class}, maxRetries = 7)
public Connection serviceA() {
    Connection conn = null;
    counterForInvokingServiceA++;
    conn = connectionService();
    return conn;
}
 
Example 23
Source Project: quarkus   Source File: CircuitBreakerBean.java    License: Apache License 2.0 5 votes vote down vote up
@CircuitBreaker(requestVolumeThreshold = 5)
public void breakCircuit() {
    if (!breakTheCircuit.getAndSet(true)) {
        return;
    }
    throw new RuntimeException("let's break it !");
}
 
Example 24
@Deployment
public static WebArchive deploy() {
    
    final Asset config = new DisableConfigAsset()
            .disable(Retry.class)
            .disable(CircuitBreaker.class)
            .disable(Timeout.class)
            .disable(Asynchronous.class)
            .disable(Fallback.class)
            .disable(Bulkhead.class)
            .enable(DisableAnnotationClient.class, Retry.class)
            .enable(DisableAnnotationClient.class, CircuitBreaker.class)
            .enable(DisableAnnotationClient.class, Timeout.class)
            .enable(DisableAnnotationClient.class, Asynchronous.class)
            .enable(DisableAnnotationClient.class, Fallback.class)
            .enable(DisableAnnotationClient.class, Bulkhead.class)
            .disable(DisableAnnotationClient.class, "failAndRetryOnce", Retry.class)
            .disable(DisableAnnotationClient.class, "failWithCircuitBreaker", CircuitBreaker.class)
            .disable(DisableAnnotationClient.class, "failWithTimeout", Timeout.class)
            .disable(DisableAnnotationClient.class, "asyncWaitThenReturn", Asynchronous.class)
            .disable(DisableAnnotationClient.class, "failRetryOnceThenFallback", Fallback.class)
            .disable(DisableAnnotationClient.class, "waitWithBulkhead", Bulkhead.class);

    final ConfigAnnotationAsset mpAnnotationConfig = new ConfigAnnotationAsset()
        .setValue(DisableAnnotationClient.class,"failWithTimeout",Timeout.class,getConfig().getTimeoutInStr(500))
        .mergeProperties(((DisableConfigAsset) config).getProps());

    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGloballyEnableClassDisableMethod.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(mpAnnotationConfig, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGloballyEnableClassDisableMethod.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 25
@Deployment
public static WebArchive deploy() {
   Asset config = new DisableConfigAsset()
           .disable(DisableAnnotationClient.class, Retry.class)
           .disable(DisableAnnotationClient.class, CircuitBreaker.class)
           .disable(DisableAnnotationClient.class, Timeout.class)
           .disable(DisableAnnotationClient.class, Asynchronous.class)
           .disable(DisableAnnotationClient.class, Fallback.class)
           .disable(DisableAnnotationClient.class, Bulkhead.class)
           .enable(DisableAnnotationClient.class, "failAndRetryOnce", Retry.class)
           .enable(DisableAnnotationClient.class, "failWithCircuitBreaker", CircuitBreaker.class)
           .enable(DisableAnnotationClient.class, "failWithTimeout", Timeout.class)
           .enable(DisableAnnotationClient.class, "asyncWaitThenReturn", Asynchronous.class)
           .enable(DisableAnnotationClient.class, "failRetryOnceThenFallback", Fallback.class)
           .enable(DisableAnnotationClient.class, "waitWithBulkhead", Bulkhead.class);
    
    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableClassEnableMethod.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableClassEnableMethod.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 26
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 1)
public Connection serviceD() {
    Connection conn = null;

    counterForInvokingService++;
    conn = connectionService();

    return conn;
}
 
Example 27
@Deployment
public static WebArchive deploy() {
   Asset config = new DisableConfigAsset()
           .disable(Retry.class)
           .disable(CircuitBreaker.class)
           .disable(Timeout.class)
           .disable(Asynchronous.class)
           .disable(Fallback.class)
           .disable(Bulkhead.class)
           .enable(DisableAnnotationClient.class, "failAndRetryOnce", Retry.class)
           .enable(DisableAnnotationClient.class, "failWithCircuitBreaker", CircuitBreaker.class)
           .enable(DisableAnnotationClient.class, "failWithTimeout", Timeout.class)
           .enable(DisableAnnotationClient.class, "asyncWaitThenReturn", Asynchronous.class)
           .enable(DisableAnnotationClient.class, "failRetryOnceThenFallback", Fallback.class)
           .enable(DisableAnnotationClient.class, "waitWithBulkhead", Bulkhead.class);
    
    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGloballyEnableMethod.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGloballyEnableMethod.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 28
@Deployment
public static WebArchive deploy() {
   Asset config = new DisableConfigAsset()
           .disable(Retry.class)
           .disable(CircuitBreaker.class)
           .disable(Timeout.class)
           .disable(Asynchronous.class)
           .disable(Fallback.class)
           .disable(Bulkhead.class)
           .enable(DisableAnnotationClient.class, Retry.class)
           .enable(DisableAnnotationClient.class, CircuitBreaker.class)
           .enable(DisableAnnotationClient.class, Timeout.class)
           .enable(DisableAnnotationClient.class, Asynchronous.class)
           .enable(DisableAnnotationClient.class, Fallback.class)
           .enable(DisableAnnotationClient.class, Bulkhead.class);
    
    JavaArchive testJar = ShrinkWrap
        .create(JavaArchive.class, "ftDisableGlobalEnableClass.jar")
        .addClasses(DisableAnnotationClient.class)
        .addPackage(Packages.UTILS)
        .addAsManifestResource(config, "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
        .as(JavaArchive.class);

    WebArchive war = ShrinkWrap
        .create(WebArchive.class, "ftDisableGlobalEnableClass.war")
        .addAsLibrary(testJar);
    return war;
}
 
Example 29
/**
 * Invokes connection service and increases the counter for invocations of serviceC and connection service
 * @return Always throws exception
 */
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
public Connection serviceC() {
    Connection conn = null;
    counterForInvokingServiceC++;
    conn = connectionService();

    return conn;
}
 
Example 30
/**
 * This method's circuit breaker moves from closed to open after 10 consecutive failures,
 * unless failureRatio is configured differently.
 */
@CircuitBreaker(requestVolumeThreshold = 10, failureRatio = 1.0)
public void failureRatioMethod(boolean fail) {
    if (fail) {
        throw new TestConfigExceptionA();
    }
}