How to create a thread safe client in RESTEasy in EAP 7?

Solution Unverified - Updated

Environment

  • JBoss Enterprise Application Platform (EAP)
    • 7.x

Issue

  • We need to access a Rest service from a client deployed on JBoss. We plan to use RESTEasy implementation shipped with EAP, how can we make our clients thread safe?

Resolution

If you create your client using the ResteasyClientBuilder and set the connectionPoolSize greater than zero, then it will automatically use the PoolingClientConnectionManager which is thread safe.

So, taking the example code from Content from docs.jboss.org is not included.RESTeasy 3.x documentation:

            Client client = ClientBuilder.newBuilder().build();
            WebTarget target = client.target("http://foo.com/resource");
            Response response = target.request().get();
            String value = response.readEntity(String.class);
            response.close();  // You should close connections!

            ResteasyClient client = new ResteasyClientBuilder().build();
            ResteasyWebTarget target = client.target("http://foo.com/resource");

To make it use the PoolingClientConnectionManager we add in a call to set the connection pool size to whatever amount is desired to accommodate the number of client threads you expect to have. We also need to set the maxPooledPerRoute which controls how many of the pooled connections can be connections to the same route. If all the connections will be to the same route, then both parameters would have the same value.

So we replace this line:

ResteasyClient client = new ResteasyClientBuilder().build();

with this line instead:

ResteasyClient client = new ResteasyClientBuilder().connectionPoolSize(20).maxPooledPerRoute(20).build();

Root Cause

By default RESTeasy will use a single connection to make HTTP requests.

Category

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.