Labeo
Labeo

Reputation: 6349

how to reuse tcp session in java for client in javax.ws.rs.client

i am trying to make 10 requests repeatedly on https service, i am able to do it but i am using 10 tcp connections for this. I want to reuse the same tcp connection created at start for the 10 requests, how to do it for below code

here client is javax.ws.rs.client

java code:

static SslConfigurator sslConfig = SslConfigurator
  .newInstance()
  .securityProtocol("TLS")
  .keyStoreFile("/path")
  .keyStorePassword("password")
  .keyStoreType("JKS")
  .trustStoreFile("/path");

static SSLContext sslCtx = sslConfig.createSSLContext();
static Client client = ClientBuilder.newBuilder().sslContext(sslCtx).build();            

for (i = 0; i < 10; i++) {
  Response response = client.target(target).path(path)
    .request(MediaType.APPLICATION_JSON)
    .post(Entity.entity(jsonRequest.toString(), MediaType.APPLICATION_JSON));
}

Upvotes: 2

Views: 1731

Answers (2)

sibnick
sibnick

Reputation: 4305

There is good article about it: Setting up jersey client 2.0 to use httpclient, timeouts, and max connections But actually it is outdated now. Sample for current Jersey client:

static PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
static Client client;
static{
    connectionManager.setMaxTotal(100);
    connectionManager.setDefaultMaxPerRoute(10);
    //you can provide per route settings
    //connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("localhost")), 40);

    SslConfigurator sslConfig = SslConfigurator.newInstance()
            .securityProtocol("TLS")
            .keyStoreFile("/path")
            .keyStorePassword("password")
            .keyStoreType("JKS")
            .trustStoreFile("/path");

    ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
    clientConfig.connectorProvider(new ApacheConnectorProvider());
    client = ClientBuilder.newBuilder().withConfig(clientConfig).sslContext(sslConfig.createSSLContext()).build();
}

Also you should call response.close(); to mark connection as free.

By default you use BasicHttpClientConnectionManager. It has following notice: This connection manager will make an effort to reuse the connection for subsequent requests with the same HttpRoute route. It will, however, close the existing connection and open it for the given route, if the route of the persistent connection does not match that of the connection request

So in simple situation connection is reused by default.

Upvotes: 3

sinclair
sinclair

Reputation: 2861

Just guessing, but you could try this:

Request req =  (Request) client.target(target).path(path).request(MediaType.APPLICATION_JSON);
for (i = 0; i < 10; i++ {
  Response response = req.post(
    Entity.entity(jsonRequest.toString(), MediaType.APPLICATION_JSON));
}

Upvotes: 1

Related Questions