Reputation: 13040
In the Play documentation there is this example:
public class AsyncTest extends Controller {
public static void remoteData() {
F.Promise<WS.HttpResponse> r1 = WS.url("http://example.org/1").getAsync();
F.Promise<WS.HttpResponse> r2 = WS.url("http://example.org/2").getAsync();
F.Promise<WS.HttpResponse> r3 = WS.url("http://example.org/3").getAsync();
F.Promise<List<WS.HttpResponse>> promises = F.Promise.waitAll(r1, r2, r3);
// Suspend processing here, until all three remote calls are complete.
List<WS.HttpResponse> httpResponses = await(promises);
render(httpResponses);
}
}
In the above example 3 new HTTP
connections to example.org
are created, correct?
Is there any way to create a pool of connections on start up, and then just grab and reuse connections from that pool instead of creating and tearing down connections repeatedly?
Ideally I can have multiple pools of connections, e.g. a pool of HTTP connection, a pool of DB connections, etc. How can I do that?
Thanks.
Upvotes: 1
Views: 2416
Reputation: 2224
In your example, you aren't getting connections, you're getting HttpResponses, which are an answer to the specific GET request that you issued on the given URL. Because the API you're using is connection-agnostic, the underlying framework could create 3 separate connections or it could reuse a single connection for all 3, and you should get the same answer.
I don't know what the framework is doing under the hood, but I bet it's pretty good.
However, if you want to manually establish a set of resources on application startup (maybe TCP connections to worker nodes?), you can initialize anything on application start as shown below:
import play.jobs.Job;
import play.jobs.OnApplicationStart;
@OnApplicationStart
public class InitializeConnectionPool extends Job {
@Override
public void doJob() {
//initialize your connection pools here, storing them in a static variable
}
}
Upvotes: 1