gpt4 book ai didi

java - http连接池如何在 Jersey 工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:05:21 26 4
gpt4 key购买 nike

这是我的代码。

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.JerseyClient;
import org.glassfish.jersey.client.JerseyClientBuilder;

public class Jersey2HttpClient {

private static class InstanceHolder {
private static final JerseyClient INSTANCE = createClient();

private static JerseyClient createClient() {
ClientConfig clientConfig = new ClientConfig();
clientConfig.property(ClientProperties.READ_TIMEOUT, 20000);
clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 20000);
PoolingHttpClientConnectionManager connectionManager =
new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(200);
connectionManager.setDefaultMaxPerRoute(50);
clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
clientConfig.connectorProvider(new ApacheConnectorProvider());

JerseyClient client = JerseyClientBuilder.createClient(clientConfig);
client.register(RequestLogger.requestLoggingFilter);
return client;
}
}

public static JerseyClient getInstance() {
return InstanceHolder.INSTANCE;
}
}

我有以下问题。

  1. 如果在创建“连接池对象”时每次都将相同的客户端返回(通过 getInstance())到调用线程?似乎同一个对象(客户端)用于连接。

  2. 执行以下代码时究竟发生了什么。

    JerseyClient client = JerseyClientBuilder.createClient(clientConfig);

换句话说,为什么创建客户端是一项昂贵的操作?我什至还没有提到 url 或请求。

抱歉我对这个问题的了解不多。

最佳答案

Client 实例是重量级的

Client的初始化实例可能是一项昂贵的操作,因为 Client s 是管理与服务器的底层通信基础设施的重量级对象。

您应该只创建少量 Client实例并在可能的情况下重用它们。 documentation陈述如下:

Clients are heavy-weight objects that manage the client-side communication infrastructure. Initialization as well as disposal of a Client instance may be a rather expensive operation. It is therefore advised to construct only a small number of Client instances in the application. Client instances must be properly closed before being disposed to avoid leaking resources.

使用ApacheConnectorProvider

默认情况下,Jersey 中的传输层由HttpURLConnection 提供。 .此支持在 Jersey 通过 HttpUrlConnectorProvider 实现.如果需要,您可以替换默认连接器。

Jersey 通过 ApacheConnectorProvider 与 Apache HTTP 客户端集成.要使用它,请确保您具有以下依赖项:

<dependency>
<groupId>org.glassfish.jersey.connectors</groupId>
<artifactId>jersey-apache-connector</artifactId>
<version>2.23.2</version>
</dependency>

在您的代码中,您实例化了一个 PoolingHttpClientConnectionManager但你没有在任何地方使用它。将以下行添加到您的代码中:

clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
clientConfig.connectorProvider(new ApacheConnectorProvider());

有关更多详细信息,请参阅 Jersey documentation about connectors .

关于java - http连接池如何在 Jersey 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38872832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com