如何限制泽西岛2连接

时间:2014-12-17 00:46:53

标签: java connection jersey-2.0

我使用的代码类似于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循环稍微修改了原始代码。这个想法是泽西岛只生成一个连接,而不是50。

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

如何只有一个连接,然后将其用于每个通信事务?

最糟糕的是,我想关闭连接,但这看起来很傻。创建连接会有很多开销(如果没有其他任何内容并且关闭它,则在守护进程上)。

守护程序报告&#34;允许连接&#34;在终端窗口(CENTOS 7,但没关系)。我通常从Windows 7桌面运行客户端。我在Eclipse Luna中使用Java 8。经常发生的事情是守护进程会说&#34;达到最大连接数&#34;并且不要做好事。

1 个答案:

答案 0 :(得分:1)

我尚未完全测试,但答案在于此other StackOverflow票。

我必须使用ApacheConnectorProvider对象。

Jersey帮助文档,第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. 

我正在进行跨原始资源共享,所以我使用的简单方法不稳定。在我的小applet上使用Apache Connector工作。我能够使用for循环,迭代次数为500并且没有问题,只需要现在就尝试真正的代码。