Ameni HADRICH
Ameni HADRICH

Reputation: 17

How to launch multiple web rest services with only one client

I am interested in developing a web application. I need to invoke ten web services at the same time, and with a single JAX-RS client.

Here is my code:

public static void main(String[] args)  {
for (int i = 1; i <= 10; i++) {
launcherPS(i)
}

static void launcherPS(int id){
        ClientConfig config = new ClientConfig();
        Client client = ClientBuilder.newClient(config);
        String name="LampPostZ"+id;
        WebTarget target = client.target(getBaseURI(name));

        System.out.println();
        System.out.println("Launching of PresenceSensor "+id+" .........");
        target.path("PresenceSensor/"+id).path("change").request()
                    .accept(MediaType.TEXT_PLAIN).get(String.class);    
    }
    private static URI getBaseURI(String project) {
        return UriBuilder.fromUri("http://localhost:8081/"+project).build();                                                            
    }
}

This code allows, invoking the second service except that the first terminates its operation. But, I need to launch them at the same time. Thank you for your help.

Upvotes: 0

Views: 49

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40318

If you are on JEE7/JAX-RS 2.0, you can use the async() method:

target.path("PresenceSensor/"+id).path("change").request()
                .accept(MediaType.TEXT_PLAIN)
                .async()
                .get(/* see Javadocs for various options! */);

Generally this returns a Future. See details in JAX-RS 2.x specs, chapter 8.4.

If on the other hand you are lucky enough to be using JEE8/JAX-RS 2.1, you can make use of the new rx() method, which can give you a CompletionStage or even richer RX things:

target.path("PresenceSensor/"+id).path("change").request()
                .accept(MediaType.TEXT_PLAIN)
                .rx() // ONLY JAX-RS 2.1
                .get(/* see Javadocs for various options! */);

See JAX-RS 2.1 specs, chapter 5.7.

NOTE: If you want to do something with the results of the invocations, you will need to adjust the code accordingly, e.g. compose the various CompletionStages to be notified when all finish.

Upvotes: 1

Related Questions