Skip to content

Latest commit

 

History

History
519 lines (388 loc) · 29.5 KB

README.adoc

File metadata and controls

519 lines (388 loc) · 29.5 KB

Building fault-tolerant microservices with the @Fallback annotation

Note
This repository contains the guide documentation source. To view the guide in published form, view it on the Open Liberty website.

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 your Open Liberty.

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

link:finish/resources/CustomConfigSource.json[role=include]

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

You do not need to restart the Liberty instance. 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.

Enabling fault tolerance

Navigate to the start directory to begin.

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 configuration file, 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 Liberty instance. 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 Liberty instance 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

link:finish/src/main/java/io/openliberty/guides/system/SystemResource.java[role=include]

CustomConfigSource.json

link:finish/resources/CustomConfigSource.json[role=include]

SystemClient.java

link:finish/src/main/java/io/openliberty/guides/inventory/client/SystemClient.java[role=include]

server.xml

link:finish/src/main/liberty/config/server.xml[role=include]

pom.xml

link:finish/pom.xml[role=include]

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

link:finish/src/main/java/io/openliberty/guides/inventory/InventoryManager.java[role=include]

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

The @Fallback annotation provides two parameters, applyOn and skipOn, which allow you to configure which exceptions trigger a fallback and which exceptions do not, respectively. In this example, the get() method throws IOException when the system service is unavailable, and throws UnknownHostException when the system service cannot be found on the specified host. The fallbackForGet() method can handle the first case, but not the second.

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

link:finish/src/main/liberty/config/server.xml[role=include]

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 configuration element provides basic security to secure the Liberty. When you go to the /metrics endpoint, use the credentials that are defined in the Liberty’s 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.

When the Liberty instance 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?scope=base 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 base_ft_invocations_total counter
base_ft_invocations_total{fallback="notApplied",method="io.openliberty.guides.inventory.InventoryManager.get",result="valueReturned"} 1
base_ft_invocations_total{fallback="applied",method="io.openliberty.guides.inventory.InventoryManager.get",result="valueReturned"} 0
base_ft_invocations_total{fallback="notApplied",method="io.openliberty.guides.inventory.InventoryManager.get",result="exceptionThrown"} 0
base_ft_invocations_total{fallback="applied",method="io.openliberty.guides.inventory.InventoryManager.get",result="exceptionThrown"} 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 puts 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

link:finish/resources/CustomConfigSource.json[role=include]

InventoryManager.java

link:finish/src/main/java/io/openliberty/guides/inventory/InventoryManager.java[role=include]

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?scope=base URL again. See the following sample outputs for the @Fallback annotated method and the fallback method after a fallback occurs:

# TYPE base_ft_invocations_total counter
base_ft_invocations_total{fallback="notApplied",method="io.openliberty.guides.inventory.InventoryManager.get",result="valueReturned"} 1
base_ft_invocations_total{fallback="applied",method="io.openliberty.guides.inventory.InventoryManager.get",result="valueReturned"} 1
base_ft_invocations_total{fallback="notApplied",method="io.openliberty.guides.inventory.InventoryManager.get",result="exceptionThrown"} 0
base_ft_invocations_total{fallback="applied",method="io.openliberty.guides.inventory.InventoryManager.get",result="exceptionThrown"} 0

From the output, the base_ft_invocations_total{fallback="notApplied",method="io.openliberty.guides.inventory.InventoryManager.get",result="valueReturned"} data shows that the get() method was called once without triggering a fallback method. The base_ft_invocations_total{fallback="applied",method="io.openliberty.guides.inventory.InventoryManager.get",result="valueReturned"} data indicates that the get() method was called once and the fallback fallbackForGet() method was triggered.

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

FaultToleranceIT.java

link:finish/src/test/java/it/io/openliberty/guides/faulttolerance/FaultToleranceIT.java[role=include]

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 testFallbackSkipForGet() test case sends a request to the inventory service to get the system properties for an incorrect hostname (unknown). Then, it confirms that the fallback method has not been called by asserting that the response’s status code is 404 with an error message in the response body.

The @Test annotations indicate that the methods automatically execute 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.

If the tests pass, you see a similar output to the following example:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.faulttolerance.FaultToleranceIT
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.517 sec - in it.io.openliberty.guides.faulttolerance.FaultToleranceIT
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: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.396 sec - in it.io.openliberty.guides.inventory.InventoryEndpointIT

Results :

Tests run: 6, 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() and testFallbackSkipForGet() test cases.

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.