Reactive, Asynchronous JAX-RS Client with Thread Pool aka Bulkheads 📎
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.