okhttp3.ConnectionPool类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(7.4k)|赞(0)|评价(0)|浏览(761)

本文整理了Java中okhttp3.ConnectionPool类的一些代码示例,展示了ConnectionPool类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ConnectionPool类的具体详情如下:
包路径:okhttp3.ConnectionPool
类名称:ConnectionPool

ConnectionPool介绍

[英]Manages reuse of HTTP and SPDY connections for reduced network latency. HTTP requests that share the same Address may share a Connection. This class implements the policy of which connections to keep open for future use.

The #getDefault() uses system properties for tuning parameters:

  • http.keepAlive true if HTTP and SPDY connections should be pooled at all. Default is true.
  • http.maxConnections maximum number of idle connections to each to keep in the pool. Default is 5.
  • http.keepAliveDuration Time in milliseconds to keep the connection alive in the pool before closing it. Default is 5 minutes. This property isn't used by HttpURLConnection.

The default instance doesn't adjust its configuration as system properties are changed. This assumes that the applications that set these parameters do so before making HTTP connections, and that this class is initialized lazily.
[中]管理HTTP和SPDY连接的重用,以减少网络延迟。共享相同地址的HTTP请求可能共享一个连接。此类实现了将哪些连接保持打开以供将来使用的策略。
#getDefault()使用系统属性来调整参数:
*http。如果HTTP和SPDY连接应合并,则keepAlive true。默认值为true。
*http。maxConnections池中要保留的每个连接的最大空闲连接数。默认值为5。
*http。keepAliveDuration在关闭连接之前保持连接在池中活动的时间(以毫秒为单位)。默认值为5分钟。HttpURLConnection未使用此属性。
默认实例不会随着系统属性的更改而调整其配置。这假设设置这些参数的应用程序在进行HTTP连接之前进行设置,并且该类是惰性初始化的。

代码示例

代码示例来源:origin: prestodb/presto

@Override
public void close()
{
  httpClient.dispatcher().executorService().shutdown();
  httpClient.connectionPool().evictAll();
}

代码示例来源:origin: apache/nifi

private OkHttpClient createOkHttpClient(final NiFiProperties properties) {
  final String connectionTimeout = properties.getClusterNodeConnectionTimeout();
  final long connectionTimeoutMs = FormatUtils.getTimeDuration(connectionTimeout, TimeUnit.MILLISECONDS);
  final String readTimeout = properties.getClusterNodeReadTimeout();
  final long readTimeoutMs = FormatUtils.getTimeDuration(readTimeout, TimeUnit.MILLISECONDS);
  OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient().newBuilder();
  okHttpClientBuilder.connectTimeout(connectionTimeoutMs, TimeUnit.MILLISECONDS);
  okHttpClientBuilder.readTimeout(readTimeoutMs, TimeUnit.MILLISECONDS);
  okHttpClientBuilder.followRedirects(true);
  final int connectionPoolSize = properties.getClusterNodeMaxConcurrentRequests();
  okHttpClientBuilder.connectionPool(new ConnectionPool(connectionPoolSize, 5, TimeUnit.MINUTES));
  final Tuple<SSLSocketFactory, X509TrustManager> tuple = createSslSocketFactory(properties);
  if (tuple != null) {
    okHttpClientBuilder.sslSocketFactory(tuple.getKey(), tuple.getValue());
  }
  return okHttpClientBuilder.build();
}

代码示例来源:origin: square/okhttp

@Override public boolean connectionBecameIdle(
  ConnectionPool pool, RealConnection connection) {
 return pool.connectionBecameIdle(connection);
}

代码示例来源:origin: fabric8io/kubernetes-client

public static boolean isHttpsAvailable(Config config) {
  Config sslConfig = new ConfigBuilder(config)
      .withMasterUrl(Config.HTTPS_PROTOCOL_PREFIX + config.getMasterUrl())
      .withRequestTimeout(1000)
      .withConnectionTimeout(1000)
      .build();
  OkHttpClient client = HttpClientUtils.createHttpClient(config);
  try {
    Request request = new Request.Builder().get().url(sslConfig.getMasterUrl())
        .build();
    Response response = client.newCall(request).execute();
    try (ResponseBody body = response.body()) {
     return response.isSuccessful();
    }
  } catch (Throwable t) {
    LOG.warn("SSL handshake failed. Falling back to insecure connection.");
  } finally {
    if (client != null && client.connectionPool() != null) {
      client.connectionPool().evictAll();
    }
  }
  return false;
}

代码示例来源:origin: prestodb/presto

private static QueryId startQuery(String sql, DistributedQueryRunner queryRunner)
  OkHttpClient httpClient = new OkHttpClient();
  try {
    ClientSession clientSession = new ClientSession(
    httpClient.dispatcher().executorService().shutdown();
    httpClient.connectionPool().evictAll();

代码示例来源:origin: Clarifai/clarifai-java

private static void closeOkHttpClient(@NotNull OkHttpClient client) {
 client.dispatcher().executorService().shutdown();
 client.connectionPool().evictAll();
 final Cache cache = client.cache();
 if (cache != null) {
  try {
   cache.close();
  } catch (IOException ignored) {
  }
 }
}

代码示例来源:origin: stackoverflow.com

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectionPool(new ConnectionPool());

代码示例来源:origin: square/okhttp

private void close() {
 client.connectionPool().evictAll(); // Close any persistent connections.
}

代码示例来源:origin: xjdr/xio

private void aggressivelyCloseClients() throws Exception {
 clients.forEach(
   client -> {
    client.dispatcher().executorService().shutdown();
    Observable.interval(100, TimeUnit.MILLISECONDS)
      .takeUntil(
        i -> {
         boolean canEvict =
           client.connectionPool().idleConnectionCount()
             == client.connectionPool().connectionCount();
         client.connectionPool().evictAll();
         return canEvict;
        })
      .timeout(15, TimeUnit.SECONDS)
      .blockingSubscribe();
   });
}

代码示例来源:origin: square/retrofit

public static void main(String... args) throws Exception {
 Dispatcher dispatcher = new Dispatcher(Executors.newFixedThreadPool(20));
 dispatcher.setMaxRequests(20);
 dispatcher.setMaxRequestsPerHost(1);
 OkHttpClient okHttpClient = new OkHttpClient.Builder()
   .dispatcher(dispatcher)
   .connectionPool(new ConnectionPool(100, 30, TimeUnit.SECONDS))
   .build();
 Retrofit retrofit = new Retrofit.Builder()
   .baseUrl(HttpUrl.get("https://example.com/"))
   .addConverterFactory(PageAdapter.FACTORY)
   .client(okHttpClient)
   .build();
 PageService pageService = retrofit.create(PageService.class);
 Crawler crawler = new Crawler(pageService);
 crawler.crawlPage(HttpUrl.get(args[0]));
}

代码示例来源:origin: square/okhttp

private static void testClient(List<String> urls, OkHttpClient client) {
 try {
  for (String url : urls) {
   sendRequest(client, url);
  }
 } finally {
  client.dispatcher.executorService().shutdownNow();
  client.connectionPool.evictAll();
 }
}

代码示例来源:origin: square/okhttp

@Override public void put(ConnectionPool pool, RealConnection connection) {
 pool.put(connection);
}

代码示例来源:origin: square/okhttp

if (pruneAndGetAllocationCount(connection, now) > 0) {
 inUseConnectionCount++;
 continue;

代码示例来源:origin: szyn/digdag-slack

private void postToSlack(String url, String payload)
  {
    RequestBody body = new FormBody.Builder()
        .add("payload", payload)
        .build();
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    Call call = singletonInstance.newCall(request);
    try (Response response = call.execute()) {
      if (!response.isSuccessful()) {
        String message = "status: " + response.code() + ", message: " + response.body().string();
        throw new IOException(message);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      singletonInstance.connectionPool().evictAll();
    }
  }
}

代码示例来源:origin: prestosql/presto

private static QueryId startQuery(String sql, DistributedQueryRunner queryRunner)
  OkHttpClient httpClient = new OkHttpClient();
  try {
    ClientSession clientSession = new ClientSession(
    httpClient.dispatcher().executorService().shutdown();
    httpClient.connectionPool().evictAll();

代码示例来源:origin: iNPUTmice/caas

private static void shutdown(OkHttpClient client) throws IOException {
    client.dispatcher().executorService().shutdown();
    client.connectionPool().evictAll();
    final Cache cache = client.cache();
    if (cache != null) {
      cache.close();
    }
  }
}

代码示例来源:origin: googlemaps/google-maps-services-java

@Override
public void shutdown() {
 executorService.shutdown();
 client.connectionPool().evictAll();
}

代码示例来源:origin: testcontainers/testcontainers-java

.connectionPool(new ConnectionPool(0, 1, TimeUnit.SECONDS))
.dns(hostname -> {
  if (hostname.endsWith(SOCKET_SUFFIX)) {

代码示例来源:origin: com.squareup.okhttp3/okhttp

@Override public void put(ConnectionPool pool, RealConnection connection) {
 pool.put(connection);
}

代码示例来源:origin: com.squareup.okhttp3/okhttp

if (pruneAndGetAllocationCount(connection, now) > 0) {
 inUseConnectionCount++;
 continue;

相关文章