I have a trivial "Hello World!" REST service which uses the microprofile for fault-tolerance, in particular, the @Fallback annotation
// HelloApplication.java
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/api")
public class HelloApplication extends Application {
}
// HelloRest.java
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@ApplicationScoped
@Path("/")
public class HelloRest {
final HelloService client = new HelloService();
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/hello")
public String sayHello() {
return client.lookupMessage();
}
}
// HelloService.java
import org.eclipse.microprofile.faulttolerance.Fallback;
import javax.enterprise.context.ApplicationScoped;
import java.util.Random;
@ApplicationScoped
public class HelloService {
@Fallback(fallbackMethod = "fallbackMessage")
public String lookupMessage() {
int rand = new Random().nextInt() % 10;
if (rand <= 3) {
return "Hello World!";
}
throw new RuntimeException("message lookup failed");
}
public String fallbackMessage() {
return "fallback message";
}
}
I build it with gradle and run it using the thorntail hollow jar.
$ java -jar microprofile-hollow-thorntail.jar my-trivial-hello-service.war
I'd expect
curl http://localhost:8080/api/hello
to return "Hello World!" for 30% of the invocations, and "fallback message" for the remaining 70%. Instead I get a RuntimeException
in 70% of the cases.
How do I have to start and/or configure thorntail in order to activate the microprofile fraction for my trivial WAR?
You need to replace
final HelloService client = new HelloService();
with
@Inject
HelloService client;
Why? Because all the CDI magic (in this case, a CDI interceptor that implements the fault tolerance strategy) can only happen if a CDI proxy (I think the CDI spec calls it "contextual reference") is used. If you construct the instance manually, you call the method directly instead of going through the proxy, effectively bypassing everything that CDI guarantees for you.