【问题标题】:How to limit Jersey 2 connections如何限制 Jersey 2 连接
【发布时间】:2014-12-18 08:46:35
【问题描述】:

我使用的代码与this 问题中的代码相似。

问题的代码形式的副本已注释掉属性,因为我已经注释掉了。

import javax.ws.rs.client.Client;

public static void main(String[] args)
{
    Client client = ClientBuilder.newClient();

    //client.property(ClientProperties.CONNECT_TIMEOUT, 1000);
    //client.property(ClientProperties.READ_TIMEOUT, 1000);

    WebTarget target = client.target("http://1.2.3.4:8080");
    target = target.queryParam("paramname", "paramvalue");
    target = target.queryParam("paramname2", "paramvalue2");

    try
    {
        String responseMsg;
        for (int i = 0; i < 50; i++)
            responseMsg = target.request(MediaType.APPLICATION_XML).get();

        System.out.println("responseMsg: " + responseMsg);
    }

    catch (ProcessingException pe)
    {
        pe.printStackTrace();
    }
}

我通过添加一个 for 循环稍微修改了原始代码。这个想法是 Jersey 只生成一个连接,而不是 50 个。

我遇到的问题是,我与之通信的守护进程报告说我在每次调用时都创建了一个新连接。

我怎样才能只有一个连接,然后将其用于每个通信事务?

在最坏的情况下,我想关闭连接,但这似乎很愚蠢。创建连接有很多开销(在守护进程上,如果没有其他内容并关闭它)。

守护程序在终端窗口(CENTOS 7,但没关系)上报告“允许连接”。我通常在我的 Windows 7 桌面上运行客户端。我将 Java 8 与 Eclipse Luna 一起使用。经常发生的是守护进程会说“已达到最大连接数”,然后继续做不好的事情。

【问题讨论】:

    标签: java connection jersey-2.0


    【解决方案1】:

    我还没有完全测试,但是答案在这张other StackOverflow 票中。

    我必须使用 ApacheConnectorProvider 对象。

    泽西岛帮助文档第 5.5 节指出:

    In a simple environment, setting the property before creating the first target is sufficient, but in complex
    environments (such as application servers), where some poolable connections might exist before your
    application even bootstraps, this approach is not 100% reliable and we recommend using a different client
    transport connector, such as Apache Connector. These limitations have to be considered especially when
    invoking CORS (Cross Origin Resource Sharing) requests. 
    

    我在做跨原创资源共享,所以我使用的简单方法不稳定。在我的小程序上使用 Apache 连接器很有效。我能够使用迭代 500 次的 for 循环并且没有问题,现在只需尝试真正的代码。

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 2013-11-01
      • 2020-12-26
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多