Reactive, Asynchronous JAX-RS Client with Thread Pool aka Bulkheads

A plain Java class with injected and configurable thread pool (ManagedExecutorService):


import java.util.concurrent.CompletionStage;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;


public class ContentFetcher {

    private Client client;
    private WebTarget workshopsTarget;
    
    @Resource
    ManagedExecutorService mes;
    
    @PostConstruct
    public void initClient() {
        this.client = ClientBuilder.
                newBuilder().
                executorService(this.mes).build();
        this.workshopsTarget = this.client.target("http://workshops.adam-bien.com");
    }

    public CompletionStage<String> fetchContent() {
        return this.workshopsTarget.request().
                rx().
                get(String.class);
    }

}
        

...used by the asynchronous, reactive invoker (the method rx()).

Can be directly exposed via an ordinary JAX-RS resource:


@Path("workshops")
public class WorkshopsResource {

    @Inject
    ContentFetcher fetcher;

    @GET
    public CompletionStage<String> content() {
        return this.fetcher.fetchContent();
    }

}

The amount of parallelism is globally configurable with the default ManagedExecutorService, or by declaring dedicated ManagedExecutorService (effectively Bulkhead pattern, also covered in javaeemicro.services workshop) for each communication / IO channel.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

Comments:

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