Building fault-tolerant microservices with the @Fallback annotation

duration 20 minutes

Prerequisites:

You’ll explore how to manage the impact of failures using MicroProfile Fault Tolerance by adding fallback behavior to microservice dependencies.

What you’ll learn

You will learn how to use MicroProfile (MP) Fault Tolerance to build resilient microservices that reduce the impact from failure and ensure continued operation of services.

MP Fault Tolerance provides a simple and flexible solution to build fault-tolerant microservices. Fault tolerance leverages different strategies to guide the execution and result of logic. As stated in the MicroProfile website, retry policies, bulkheads, and circuit breakers are popular concepts in this area. They dictate whether and when executions take place, and fallbacks offer an alternative result when an execution does not complete successfully.

The application that you will be working with is an inventory service, which collects, stores, and returns the system properties. It uses the system service to retrieve the system properties for a particular host. You will add fault tolerance to the inventory service so that it reacts accordingly when the system service is unavailable.

You will use the @Fallback annotations from the MicroProfile Fault Tolerance specification to define criteria for when to provide an alternative solution for a failed execution.

You will also see the application metrics for the fault tolerance methods that are automatically enabled when you add the MicroProfile Metrics feature to the server.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-microprofile-fallback.git
cd guide-microprofile-fallback

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Try what you’ll build

The finish directory in the root of this guide contains the finished implementation for the application. Give it a try before you proceed with building your own.

To try out the application, first go to the finish directory and run the following Maven goal to build the application and deploy it to Open Liberty:

mvn liberty:run

Point your browser to the http://localhost:9080/inventory/systems/localhost URL, which accesses the inventory service with a localhost hostname. You see the system properties for this host. When you visit this URL, some of these system properties, such as the OS name and user name, are automatically stored in the inventory.

Update the CustomConfigSource configuration file.
resources/CustomConfigSource.json

CustomConfigSource.json

1{"config_ordinal":500,
2"io_openliberty_guides_system_inMaintenance":false}

Change the io_openliberty_guides_system_inMaintenance property from false to true and save the file.

You do not need to restart the server. Next, return to your browser and point back to the http://localhost:9080/inventory/systems/localhost URL. The fallback mechanism is triggered because the system service is now in maintenance. You see the cached properties for this localhost.

When you are done checking out the application, go to the CustomConfigSource.json file again.

Update the CustomConfigSource configuration file.
resources/CustomConfigSource.json

Change the io_openliberty_guides_system_inMaintenance property from true to false to set this condition back to its original value.

After you are done checking out the application, stop the Open Liberty server by pressing CTRL+C in the shell session where you ran the server. Alternatively, you can run the liberty:stop goal from the finish directory in another shell session:

mvn liberty:stop

Enabling fault tolerance

Navigate to the start directory to begin.

Start Open Liberty in development mode, which starts the Open Liberty server and listens for file changes:

mvn liberty:dev

The MicroProfile Fault Tolerance API is included in the MicroProfile dependency that is specified in your pom.xml file. Look for the dependency with the microprofile artifact ID. This dependency provides a library that allows you to use fault tolerance policies in your microservices.

You can also find the mpFaultTolerance feature in your src/main/liberty/config/server.xml server configuration, which turns on MicroProfile Fault Tolerance capabilities in Open Liberty.

To easily work through this guide, the two provided microservices are set up to run on the same server. To simulate the availability of the services and then to enable fault tolerance, dynamic configuration with MicroProfile Configuration is used so that you can easily take one service or the other down for maintenance. If you want to learn more about setting up dynamic configuration, see Configuring microservices.

The following two steps set up the dynamic configuration on the system service and its client. You can move on to the next section, which adds the fallback mechanism on the inventory service.

First, the src/main/java/io/openliberty/guides/system/SystemResource.java file has the isInMaintenance() condition, which determines that the system properties are returned only if you set the io_openliberty_guides_system_inMaintenance configuration property to false in the CustomConfigSource file. Otherwise, the service returns a Status.SERVICE_UNAVAILABLE message, which makes it unavailable.

Next, the src/main/java/io/openliberty/guides/inventory/client/SystemClient.java file makes a request to the system service through the MicroProfile Rest Client API. If you want to learn more about MicroProfile Rest Client, you can follow the Consuming RESTful services with template interfaces guide. The system service as described in the SystemResource.java file may return a Status.SERVICE_UNAVAILABLE message, which is a 503 status code. This code indicates that the server being called is unable to handle the request because of a temporary overload or scheduled maintenance, which would likely be alleviated after some delay. To simulate that the system is unavailable, an IOException is thrown.

The InventoryManager class calls the getProperties() method in the SystemClient.java class. You will look into the InventoryManager class in more detail in the next section.

SystemResource.java

 1package io.openliberty.guides.system;
 2
 3import javax.enterprise.context.RequestScoped;
 4import javax.ws.rs.GET;
 5import javax.inject.Inject;
 6import javax.ws.rs.core.Response;
 7import javax.ws.rs.Path;
 8import javax.ws.rs.Produces;
 9import javax.ws.rs.core.MediaType;
10
11@RequestScoped
12@Path("properties")
13public class SystemResource {
14
15  @Inject
16  SystemConfig systemConfig;
17
18  @GET
19  @Produces(MediaType.APPLICATION_JSON)
20  public Response getProperties() {
21    if (!systemConfig.isInMaintenance()) {
22      return Response.ok(System.getProperties()).build();
23    } else {
24      return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
25    }
26  }
27}

CustomConfigSource.json

1{"config_ordinal":500,
2"io_openliberty_guides_system_inMaintenance":false}

SystemClient.java

 1package io.openliberty.guides.inventory.client;
 2
 3import java.util.Properties;
 4import java.io.IOException;
 5import javax.enterprise.context.Dependent;
 6import javax.ws.rs.ProcessingException;
 7import javax.ws.rs.GET;
 8import javax.ws.rs.Path;
 9import javax.ws.rs.Produces;
10import javax.ws.rs.core.MediaType;
11import org.eclipse.microprofile.rest.client.annotation.RegisterProvider;
12import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
13
14
15@RegisterRestClient
16@RegisterProvider(ExceptionMapper.class)
17@Path("/properties")
18public interface SystemClient {
19  @GET
20  @Produces(MediaType.APPLICATION_JSON)
21  public Properties getProperties()
22      throws UnknownUrlException, IOException, ProcessingException;
23}

server.xml

 1<server description="Sample Liberty server">
 2
 3  <featureManager>
 4    <feature>jaxrs-2.1</feature>
 5    <feature>jsonp-1.1</feature>
 6    <feature>cdi-2.0</feature>
 7    <feature>mpConfig-1.3</feature>
 8    <feature>mpRestClient-1.3</feature>
 9    <!-- tag::mpFaultTolerance[] -->
10    <feature>mpFaultTolerance-2.0</feature>
11    <!-- end::mpFaultTolerance[] -->
12    <!-- tag::mpMetrics[] -->
13    <feature>mpMetrics-2.0</feature>
14    <!-- end::mpMetrics[] -->
15  </featureManager>
16
17  <variable name="default.http.port" defaultValue="9080"/>
18  <variable name="default.https.port" defaultValue="9443"/>
19
20  <!-- tag::quickStartSecurity[] -->
21  <quickStartSecurity userName="admin" userPassword="adminpwd"/>
22  <!-- end::quickStartSecurity[] -->
23  <!-- tag::keyStore[] -->
24  <keyStore id="defaultKeyStore" location="key.jks" type="jks" password="mpKeystore"/>
25  <!-- end::keyStore[] -->
26
27  <httpEndpoint host="*" httpPort="${default.http.port}"
28    httpsPort="${default.https.port}" id="defaultHttpEndpoint"/>
29
30  <webApplication location="guide-microprofile-fallback.war" contextRoot="/"/>
31</server>

pom.xml

  1<?xml version='1.0' encoding='utf-8'?>
  2<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">
  3
  4  <modelVersion>4.0.0</modelVersion>
  5
  6  <groupId>io.openliberty.guides</groupId>
  7  <artifactId>guide-microprofile-fallback</artifactId>
  8  <version>1.0-SNAPSHOT</version>
  9  <packaging>war</packaging>
 10
 11  <properties>
 12    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 13    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 14    <maven.compiler.source>1.8</maven.compiler.source>
 15    <maven.compiler.target>1.8</maven.compiler.target>
 16    <failOnMissingWebXml>false</failOnMissingWebXml>
 17    <!-- Plugin versions -->
 18    <version.liberty-maven-plugin>3.1</version.liberty-maven-plugin>
 19    <version.maven-failsafe-plugin>2.22.2</version.maven-failsafe-plugin>
 20    <version.maven-war-plugin>3.2.3</version.maven-war-plugin>
 21    <version.maven-surefire-plugin>2.22.2</version.maven-surefire-plugin>
 22    <!-- Liberty configuration -->
 23    <liberty.var.default.http.port>9080</liberty.var.default.http.port>
 24    <liberty.var.default.https.port>9443</liberty.var.default.https.port>
 25  </properties>
 26
 27  <dependencies>
 28    <!-- Provided dependencies -->
 29    <dependency>
 30      <groupId>org.eclipse.microprofile</groupId>
 31      <!-- tag::microprofile[] -->
 32      <artifactId>microprofile</artifactId>
 33      <!-- end::microprofile[] -->
 34      <version>3.0</version>
 35      <type>pom</type>
 36      <scope>provided</scope>
 37    </dependency>
 38    <!-- For tests -->
 39    <dependency>
 40      <groupId>org.junit.jupiter</groupId>
 41      <artifactId>junit-jupiter-engine</artifactId>
 42      <version>5.5.2</version>
 43      <scope>test</scope>
 44    </dependency>
 45    <dependency>
 46      <groupId>org.apache.cxf</groupId>
 47      <artifactId>cxf-rt-rs-client</artifactId>
 48      <version>3.3.4</version>
 49      <scope>test</scope>
 50    </dependency>
 51    <dependency>
 52      <groupId>org.apache.cxf</groupId>
 53      <artifactId>cxf-rt-rs-extension-providers</artifactId>
 54      <version>3.3.4</version>
 55      <scope>test</scope>
 56    </dependency>
 57    <dependency>
 58      <groupId>org.glassfish</groupId>
 59      <artifactId>javax.json</artifactId>
 60      <version>1.1.4</version>
 61      <scope>test</scope>
 62    </dependency>
 63    <!-- Java utility classes -->
 64    <dependency>
 65      <groupId>org.apache.commons</groupId>
 66      <artifactId>commons-lang3</artifactId>
 67      <version>3.9</version>
 68    </dependency>
 69    <!-- Support for JDK 9 and above -->
 70    <dependency>
 71      <groupId>javax.xml.bind</groupId>
 72      <artifactId>jaxb-api</artifactId>
 73      <version>2.3.1</version>
 74            <scope>test</scope>
 75    </dependency>
 76    <dependency>
 77      <groupId>com.sun.xml.bind</groupId>
 78      <artifactId>jaxb-core</artifactId>
 79      <version>2.3.0.1</version>
 80            <scope>test</scope>
 81    </dependency>
 82    <dependency>
 83      <groupId>com.sun.xml.bind</groupId>
 84      <artifactId>jaxb-impl</artifactId>
 85      <version>2.3.2</version>
 86            <scope>test</scope>
 87    </dependency>
 88  </dependencies>
 89
 90  <build>
 91    <finalName>${project.artifactId}</finalName>
 92    <plugins>
 93      <plugin>
 94        <groupId>org.apache.maven.plugins</groupId>
 95        <artifactId>maven-war-plugin</artifactId>
 96        <version>${version.maven-war-plugin}</version>
 97      </plugin>
 98      <!-- Plugin to run unit tests -->
 99      <plugin>
100        <groupId>org.apache.maven.plugins</groupId>
101        <artifactId>maven-surefire-plugin</artifactId>
102        <version>${version.maven-surefire-plugin}</version>
103      </plugin>
104      <!-- Enable liberty-maven plugin -->
105      <plugin>
106        <groupId>io.openliberty.tools</groupId>
107        <artifactId>liberty-maven-plugin</artifactId>
108        <version>${version.liberty-maven-plugin}</version>
109      </plugin>
110      <!-- Plugin to run functional tests -->
111      <plugin>
112        <groupId>org.apache.maven.plugins</groupId>
113        <artifactId>maven-failsafe-plugin</artifactId>
114        <version>${version.maven-failsafe-plugin}</version>
115        <configuration>
116          <systemPropertyVariables>
117            <http.port>${liberty.var.default.http.port}</http.port>
118          </systemPropertyVariables>
119        </configuration>
120      </plugin>
121    </plugins>
122  </build>
123</project>

Adding the @Fallback annotation

The inventory service is now able to recognize that the system service was taken down for maintenance. An IOException is thrown to simulate the system service is unavailable. Now, set a fallback method to deal with this failure.

Replace the InventoryManager class.
src/main/java/io/openliberty/guides/inventory/InventoryManager.java

InventoryManager.java

 1package io.openliberty.guides.inventory;
 2
 3import java.io.IOException;
 4import java.util.Properties;
 5import java.util.ArrayList;
 6import java.util.Collections;
 7import java.util.List;
 8import javax.enterprise.context.ApplicationScoped;
 9import org.eclipse.microprofile.faulttolerance.Fallback;
10import io.openliberty.guides.inventory.model.*;
11
12@ApplicationScoped
13public class InventoryManager {
14
15  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
16  private InventoryUtils invUtils = new InventoryUtils();
17
18  @Fallback(fallbackMethod = "fallbackForGet")
19  public Properties get(String hostname) throws IOException {
20    return invUtils.getProperties(hostname);
21  }
22
23  public Properties fallbackForGet(String hostname) {
24    Properties properties = findHost(hostname);
25    if (properties == null) {
26      Properties msgProp = new Properties();
27      msgProp.setProperty(hostname, "System is not found in the inventory");
28      return msgProp;
29    }
30    return properties;
31  }
32
33  public void add(String hostname, Properties systemProps) {
34    Properties props = new Properties();
35    props.setProperty("os.name", systemProps.getProperty("os.name"));
36    props.setProperty("user.name", systemProps.getProperty("user.name"));
37
38    SystemData system = new SystemData(hostname, props);
39    if (!systems.contains(system)) {
40      systems.add(system);
41    }
42  }
43
44  public InventoryList list() {
45    return new InventoryList(systems);
46  }
47
48  private Properties findHost(String hostname) {
49    for (SystemData system : systems) {
50      if (system.getHostname().equals(hostname)) {
51        return system.getProperties();
52      }
53    }
54    return null;
55  }
56}

The @Fallback annotation dictates a method to call when the original method encounters a failed execution. In this example, use the fallbackForGet() method.

The fallbackForGet() method, which is the designated fallback method for the original get() method, checks to see if the system’s properties exist in the inventory. If the system properties entry is not found in the inventory, the method prints out a warning message in the browser. Otherwise, this method returns the cached property values from the inventory.

You successfully set up your microservice to have fault tolerance capability.

Enabling metrics for the fault tolerance methods

server.xml

 1<server description="Sample Liberty server">
 2
 3  <featureManager>
 4    <feature>jaxrs-2.1</feature>
 5    <feature>jsonp-1.1</feature>
 6    <feature>cdi-2.0</feature>
 7    <feature>mpConfig-1.3</feature>
 8    <feature>mpRestClient-1.3</feature>
 9    <!-- tag::mpFaultTolerance[] -->
10    <feature>mpFaultTolerance-2.0</feature>
11    <!-- end::mpFaultTolerance[] -->
12    <!-- tag::mpMetrics[] -->
13    <feature>mpMetrics-2.0</feature>
14    <!-- end::mpMetrics[] -->
15  </featureManager>
16
17  <variable name="default.http.port" defaultValue="9080"/>
18  <variable name="default.https.port" defaultValue="9443"/>
19
20  <!-- tag::quickStartSecurity[] -->
21  <quickStartSecurity userName="admin" userPassword="adminpwd"/>
22  <!-- end::quickStartSecurity[] -->
23  <!-- tag::keyStore[] -->
24  <keyStore id="defaultKeyStore" location="key.jks" type="jks" password="mpKeystore"/>
25  <!-- end::keyStore[] -->
26
27  <httpEndpoint host="*" httpPort="${default.http.port}"
28    httpsPort="${default.https.port}" id="defaultHttpEndpoint"/>
29
30  <webApplication location="guide-microprofile-fallback.war" contextRoot="/"/>
31</server>

MicroProfile Fault Tolerance integrates with MicroProfile Metrics to provide metrics for the annotated fault tolerance methods. When both the mpFaultTolerance and the mpMetrics features are included in the server.xml configuration file, the @Fallback fault tolerance annotation provides metrics that count the following things: the total number of annotated method invocations, the total number of failed annotated method invocations, and the total number of the fallback method calls.

The mpMetrics feature requires SSL and the configuration is provided for you. The quickStartSecurity and keyStore configuration elements provide basic security to secure the server. When you go to the /metrics endpoint, use the credentials that are defined in the server configuration to log in to view the data for the fault tolerance methods.

You can learn more about MicroProfile Metrics in the Providing metrics from a microservice guide. You can also learn more about the MicroProfile Fault Tolerance and MicroProfile Metrics integration in the MicroProfile Fault Tolerance specification.

Building and running the application

The Open Liberty server started in development mode at the beginning of the guide and all the changes were automatically picked up.

When the server is running, point your browser to the http://localhost:9080/inventory/systems/localhost URL. You receive the system properties of your local JVM from the inventory service. Next, point your browser to the system service URL, which is located at http://localhost:9080/system/properties, to retrieve the system properties for the specific localhost. Notice that the results from the two URLs are identical because the inventory service gets its results from calling the system service.

To see the application metrics, go to the https://localhost:9443/metrics/application URL. Log in as the admin user, and use adminpwd as the password. See the following sample outputs for the @Fallback annotated method and the fallback method before a fallback occurs:

# TYPE application:ft_io_openliberty_guides_inventory_inventory_manager_get_invocations_total counter
application:ft_io_openliberty_guides_inventory_inventory_manager_get_invocations_total 1
# TYPE application:ft_io_openliberty_guides_inventory_inventory_manager_get_invocations_failed_total counter
application:ft_io_openliberty_guides_inventory_inventory_manager_get_invocations_failed_total 0
# TYPE application:ft_io_openliberty_guides_inventory_inventory_manager_get_fallback_calls_total counter
application:ft_io_openliberty_guides_inventory_inventory_manager_get_fallback_calls_total 0

You can test the fault tolerance mechanism of your microservices by dynamically changing the io_openliberty_guides_system_inMaintenance property value to true in the resources/CustomConfigSource.json file, which turns the system service in maintenance.

Update the configuration file.
resources/CustomConfigSource.json

Change the io_openliberty_guides_system_inMaintenance property from false to true and save the file.

CustomConfigSource.json

1{"config_ordinal":500,
2"io_openliberty_guides_system_inMaintenance":false}

InventoryManager.java

 1package io.openliberty.guides.inventory;
 2
 3import java.io.IOException;
 4import java.util.Properties;
 5import java.util.ArrayList;
 6import java.util.Collections;
 7import java.util.List;
 8import javax.enterprise.context.ApplicationScoped;
 9import org.eclipse.microprofile.faulttolerance.Fallback;
10import io.openliberty.guides.inventory.model.*;
11
12@ApplicationScoped
13public class InventoryManager {
14
15  private List<SystemData> systems = Collections.synchronizedList(new ArrayList<>());
16  private InventoryUtils invUtils = new InventoryUtils();
17
18  @Fallback(fallbackMethod = "fallbackForGet")
19  public Properties get(String hostname) throws IOException {
20    return invUtils.getProperties(hostname);
21  }
22
23  public Properties fallbackForGet(String hostname) {
24    Properties properties = findHost(hostname);
25    if (properties == null) {
26      Properties msgProp = new Properties();
27      msgProp.setProperty(hostname, "System is not found in the inventory");
28      return msgProp;
29    }
30    return properties;
31  }
32
33  public void add(String hostname, Properties systemProps) {
34    Properties props = new Properties();
35    props.setProperty("os.name", systemProps.getProperty("os.name"));
36    props.setProperty("user.name", systemProps.getProperty("user.name"));
37
38    SystemData system = new SystemData(hostname, props);
39    if (!systems.contains(system)) {
40      systems.add(system);
41    }
42  }
43
44  public InventoryList list() {
45    return new InventoryList(systems);
46  }
47
48  private Properties findHost(String hostname) {
49    for (SystemData system : systems) {
50      if (system.getHostname().equals(hostname)) {
51        return system.getProperties();
52      }
53    }
54    return null;
55  }
56}

After saving the file, go back to your browser and refresh to the http://localhost:9080/inventory/systems/localhost URL to view the cached version of the properties. The fallbackForGet() method, which is the designated fallback method, is called when the system service is not available. The cached system properties contain only the OS name and user name key and value pairs.

To see that the system service is down, point your browser to the http://localhost:9080/system/properties URL again. You see that the service displays a 503 HTTP response code.

Go to the https://localhost:9443/metrics/application URL again. See the following sample outputs for the @Fallback annotated method and the fallback method after a fallback occurs:

# TYPE application:ft_io_openliberty_guides_inventory_inventory_manager_get_invocations_total counter
application:ft_io_openliberty_guides_inventory_inventory_manager_get_invocations_total 2
# TYPE application:ft_io_openliberty_guides_inventory_inventory_manager_get_invocations_failed_total counter
application:ft_io_openliberty_guides_inventory_inventory_manager_get_invocations_failed_total 0
# TYPE application:ft_io_openliberty_guides_inventory_inventory_manager_get_fallback_calls_total counter
application:ft_io_openliberty_guides_inventory_inventory_manager_get_fallback_calls_total 1

From the output, the ft_io_openliberty_guides_inventory_inventory_manager_get_invocations_total data indicates that the get() was called twice including the previous call before turning the system service in maintenance. The ft_io_openliberty_guides_inventory_inventory_manager_get_fallback_calls_total data indicates that the fallbackForGet() method was called once.

Update the configuration file.
resources/CustomConfigSource.json

After you finish, change the io_openliberty_guides_system_inMaintenance property value back to false in the resources/CustomConfigSource.json file.

Testing the application

You can test your application manually, but automated tests ensure code quality because they trigger a failure whenever a code change introduces a defect. JUnit and the JAX-RS Client API provide a simple environment for you to write tests.

Create the FaultToleranceIT class.
src/test/java/it/io/openliberty/guides/faulttolerance/FaultToleranceIT.java

The @BeforeEach and @AfterEach annotations indicate that this method runs either before or after the other test case. These methods are generally used to perform any setup and teardown tasks. In this case, the setup method creates a JAX-RS client, which makes HTTP requests to the inventory service. This client must also be registered with a JSON-P provider to process JSON resources. The teardown method simply destroys this client instance as well as the HTTP responses.

The testFallbackForGet() test case sends a request to the inventory service to get the systems properties for a hostname before and after the system service becomes unavailable. Then, it asserts outputs from the two requests to ensure that they are different from each other.

The @Test annotation indicates that the method automatically executes when your test class runs.

In addition, a few endpoint tests have been included for you to test the basic functionality of the inventory and system services. If a test failure occurs, then you might have introduced a bug into the code.

FaultToleranceIT.java

 1package it.io.openliberty.guides.faulttolerance;
 2
 3import static org.junit.jupiter.api.Assertions.assertEquals;
 4import static org.junit.jupiter.api.Assertions.assertTrue;
 5import javax.json.JsonObject;
 6import javax.ws.rs.client.Client;
 7import javax.ws.rs.client.ClientBuilder;
 8import javax.ws.rs.core.Response;
 9import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
10import org.junit.jupiter.api.AfterEach;
11import org.junit.jupiter.api.BeforeEach;
12import org.junit.jupiter.api.Test;
13
14import it.io.openliberty.guides.utils.TestUtils;
15
16public class FaultToleranceIT {
17
18    private Response response;
19    private Client client;
20
21    @BeforeEach
22    public void setup() {
23        client = ClientBuilder.newClient();
24        client.register(JsrJsonpProvider.class);
25    }
26
27    @AfterEach
28    public void teardown() {
29        client.close();
30        response.close();
31    }
32
33    @Test
34    public void testFallbackForGet() throws InterruptedException {
35        response = TestUtils.getResponse(client,
36                                         TestUtils.INVENTORY_LOCALHOST_URL);
37        assertResponse(TestUtils.baseUrl, response);
38        JsonObject obj = response.readEntity(JsonObject.class);
39        int propertiesSize = obj.size();
40        TestUtils.changeSystemProperty(TestUtils.SYSTEM_MAINTENANCE_FALSE,
41                                       TestUtils.SYSTEM_MAINTENANCE_TRUE);
42        Thread.sleep(3000);
43        response = TestUtils.getResponse(client,
44                                         TestUtils.INVENTORY_LOCALHOST_URL);
45        assertResponse(TestUtils.baseUrl, response);
46        obj = response.readEntity(JsonObject.class);
47        int propertiesSizeFallBack = obj.size();
48        assertTrue(propertiesSize > propertiesSizeFallBack,
49                   "The total number of properties from the @Fallback method "
50                 + "is not smaller than the number from the system service, as expected.");
51        TestUtils.changeSystemProperty(TestUtils.SYSTEM_MAINTENANCE_TRUE,
52                                       TestUtils.SYSTEM_MAINTENANCE_FALSE);
53        Thread.sleep(3000);
54    }
55
56    private void assertResponse(String url, Response response) {
57        assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
58    }
59}

Running the tests

Since you started Open Liberty in development mode at the start of the guide, press the enter/return key to run the tests. You see the following output:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.system.SystemEndpointIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.937 sec - in it.io.openliberty.guides.system.SystemEndpointIT
Running it.io.openliberty.guides.inventory.InventoryEndpointIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.396 sec - in it.io.openliberty.guides.inventory.InventoryEndpointIT
Running it.io.openliberty.guides.faulttolerance.FaultToleranceIT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.517 sec - in it.io.openliberty.guides.faulttolerance.FaultToleranceIT

Results :

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

To see if the tests detect a failure, comment out the changeSystemProperty() methods in the FaultToleranceIT.java file. Rerun the tests to see that a test failure occurs for the testFallbackForGet() test case.

When you are done checking out the service, exit development mode by typing q in the shell session where you ran the server, and then press the enter/return key.

Great work! You’re done!

You just learned how to build a fallback mechanism for a microservice with MicroProfile Fault Tolerance in Open Liberty and wrote a test to validate it.

You can try one of the related MicroProfile guides. They demonstrate technologies that you can learn and expand on what you built here.

Guide Attribution

Building fault-tolerant microservices with the @Fallback annotation by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star