Fetching content reactively with JAX-RS 2.1 client and Java EE 8

Java EE 8 with JAX-RS 2.1 / JSR-370 introduced a JAX-RS Client API integrated with CompletionStage (aka reactive client).

Now an asynchronous request may return a Java 8 CompletionStage which allows a pipeline-style programming:


import java.util.concurrent.CompletionStage;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;


public class ReactiveClientTest {

    private WebTarget tut;

    @Before
    public void initClient() {
        this.tut = ClientBuilder.
        newClient().target("http://airhacks.com");
    }


    @Test
    public void reactive() throws InterruptedException {
        CompletionStage<Response> stage = this.tut.
                request().
                rx().
                get();
        stage.
                thenApply(req -> req.readEntity(String.class)).
                thenAccept(System.out::println);
        Thread.sleep(500);
    }

}

The JAX-RS 2.1 client requires the following dependencies:


<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.26</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>2.26</version>        
</dependency>

See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License