Creating and pooling web targets

JAX-RS provides a Client API for creating clients to connect to the services with its fluent API approach. The instances of Client are expensive to initialize, so there should be a minimum set of it for reuse. WebTarget represents the specific URI that will be invoked so it can easily be set into the instance of the Client before requesting. For the Forecast service given in the previous section, we can implement a web target producer to create the location web target when requested.

The following code showcases the implementation of produceLocationWebTarget  :

@ApplicationScoped
public class WebTargetProducer {

private Client client;

@PostConstruct
private void postConstruct() {
this.client = ClientBuilder.newClient();
}

@Produces
@Dependent
public WebTarget produceLocationWebTarget() {
return client.target("http://localhost:8080")
.path("forecast-service")
.path("smartcity")
.path("location");
}
}

And the web target can be produced within the Forecast service, as follows:

List<Location> locations = producer.produceLocationWebTarget()
.request()
.get(new GenericType<List<Location>>() {});
..................Content has been hidden....................

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