Search code examples
javawebsphere-libertyfault-tolerancemicroprofile

How to use MicroProfile FaultTolerance in Liberty profile


I want to use the circuit break function in MP FaultTolerance feature in my web application. Now I have no idea about how to know if this function has been working in my application. And I want to track the value of MP Metrics added by MP Fault Tolerance automatically as said in https://download.eclipse.org/microprofile/microprofile-fault-tolerance-2.0/microprofile-fault-tolerance-spec.html#fallback

My application runs on WAS Liberty profile 19.0.0.6. I tried to use /metrics to get all Metrics, but only base metrics are returned. The return is as below

# TYPE base:classloader_total_loaded_class_count counter
# HELP base:classloader_total_loaded_class_count Displays the total number of classes that have been loaded since the Java virtual machine has started execution.
base:classloader_total_loaded_class_count 8853

I imported package org.eclipse.microprofile.faulttolerance. Annotation CircuitBreaker into my java code and add annotation in front of a method like this:

@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 3, failureRatio = 0.5, delay = 1000)
public void handle() throws ApiRequesterException{

    ..........
}

And I added feature in server.xml as below

<featureManager>

     <feature>mpFaultTolerance-1.1</feature>

     <feature>mpMetrics-1.1</feature>

</featureManager>
  1. How can I get the value of Metrics added by Fault Tolerance, such as ft.<name>.circuitbreaker.callsSucceeded.total, ft.<name>.circuitbreaker.callsSucceeded.total and so on.
  2. How can know the annotation CircuitBreaker is working when my application is running?

Solution

  • It looks like you've done everything right, so there are a couple of possibilities as to why you're not seeing the metrics:

    1. Metrics don't appear until the method has been called once

    2. Do you have the required features installed?

    If you don't have both mpFaultTolerance-1.1 and mpMetrics-1.1 installed, the server will still start, but you'll get a warning at the top of your messages.log saying which features couldn't start or weren't present.

    1. Is the annotated method in a CDI bean?

    Fault Tolerance is implemented using interceptors. For interception to happen, the method needs to be on a CDI bean, you need to use @Inject to inject your bean somewhere, and then you need to call the method on the instance that was injected.

    In particular, interception does not happen if:

    • you create the instance of your class using new
    • you call the annotated method from within the same class

    As far as testing whether your circuit breaker is working, the easiest way is usually to call the method and check that the metrics appear. Beyond that, you need to cause your method to fail several times and check that you start getting a CircuitBreakerOpenException.