Thursday, May 9, 2019

Resilience for Java Example

There are some good explanations of Resilience4J (see https://dzone.com/articles/resilience4j-intro and https://www.baeldung.com/resilience4j) but, my initial interest is in getting a simple example running. Here is my maven pom and simple Java class and the results.
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>r4j-example</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Maven Quick Start Archetype</name>
  <url>http://maven.apache.org</url>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  
  <dependencies>
    <dependency>
      <groupId>io.github.resilience4j</groupId>
      <artifactId>resilience4j-circuitbreaker</artifactId>
      <version>0.12.1</version>
    </dependency>
    <dependency>
      <groupId>io.github.resilience4j</groupId>
      <artifactId>resilience4j-rxjava2</artifactId>
      <version>0.13.1</version>
    </dependency>
    <dependency>
      <groupId>io.vavr</groupId>
      <artifactId>vavr</artifactId>
      <version>0.10.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
import io.github.resilience4j.circuitbreaker.*;
import io.github.resilience4j.circuitbreaker.event.CircuitBreakerEvent;
import io.github.resilience4j.circuitbreaker.event.CircuitBreakerOnStateTransitionEvent;
import io.github.resilience4j.circuitbreaker.internal.CircuitBreakerStateMachine;
import io.vavr.control.Try;

public class R4jExample {

  public static void main(String[] args) {
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();

    CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("example");

    // employ io.vavr.control.Try 
    Try result = Try.of(CircuitBreaker
      .decorateCheckedSupplier(circuitBreaker, () -> "Hello")
    ).map(value -> value + " world");

    System.out.println("this is it: " + result);

    Try result2 = Try.of(CircuitBreaker
      .decorateCheckedSupplier(circuitBreaker, () -> {
          throw new RuntimeException("BAM!");
      }));

    System.out.println("this is another: " + result2);

    Try result3 = Try.of(CircuitBreaker
      .decorateCheckedSupplier(circuitBreaker, () -> {
          throw new RuntimeException("BAM!");
      }));

    System.out.println("this is another: " + result3.getOrElse("Nothing"));
  }
}