Using third-party reactive frameworks

It's also possible to use third-party reactive frameworks with JAX-RS to instantiate a reactive invoker. RxJava (https://github.com/ReactiveX/RxJava) is one one of the most advanced reactive libraries for Java, and Jersey provides support for it by offering a custom client artifact. We will implement a reactive client by using RxJava under the hood. The client's Maven dependency definition is as follows:

<dependency>
<groupId>org.glassfish.jersey.ext.rx</groupId>
<artifactId>jersey-rx-client-rxjava2</artifactId>
<version>2.26</version>
</dependency>

jersey-rx-client-rxjava2 transitively depends on RxJava 2.0.4, so we don't need to define it in our dependency graph.

The following code gives implementation of Temperature Client:

public class TemperatureResourceAsyncClient5 {

public static void main(String... args)
throws ExecutionException, InterruptedException {

Client client = ClientBuilder.newClient()
.register(RxFlowableInvokerProvider.class);
WebTarget target = client.target("http://localhost:8080/" +
"weather-service/weather/temperature");

Invocation.Builder builder = target.request();
Flowable<Response> flowable = builder
.rx(RxFlowableInvoker.class)
.get();
flowable.subscribe(res -> {
Temperature t = res.readEntity(Temperature.class);
System.out.println(t);
});

new Thread(() -> {
try {
for (int seconds = 3; seconds > 0; seconds--) {
System.out.println(seconds + " seconds left");
Thread.sleep(1000);
}
System.out.println("Finished!");
client.close();
}
catch (Exception ignored) {}
}).start();
}
}

We first register a custom JAX-RS component, the RxFlowableInvokerProvider class, to our client container by calling the register() method. This integrates an instance of JerseyRxFlowableInvoker, which is an implementation of a reactive invoker specialized for io.reactivex.Flowable. Invoking the rx() method with the RxFlowableInvoker.class parameter returns the reactive invoker subclassed to RxFlowableInvoker, which in our case, is the same instance of JerseyRxFlowableInvoker.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.245.140