4

我正在使用 Jersey v10 并编写了以下代码。这是关闭 Jersey 客户端连接以避免内存泄漏的正确方法吗?在此之前我最终没有对他进行任何调用。

ClientConfig config = setupHttps();
    final Client c = Client.create(config);

    final WebResource r = c.resource(baseUri);
    ClientResponse response = null;
    try {
        response = r.path("/....")
                .header("contentId", id)
                .header("sid", sid).get(ClientResponse.class);
        ...



    } catch (Exception e) {
        log.error("Error returning contentServiceName.");

    } finally {
        if (response != null) {
            response.close();
        }
        if (c!= null) {
            c.destroy();
        }

    }

TIA,维杰

4

1 回答 1

8

据我所知,是的,这是关闭泽西岛客户的正确方法......但有以下注意事项。

1)您要防止的不是内存泄漏,而是连接(到您正在处理的服务器)泄漏......

2) 以下是Jersey Handbook 第 3 章中关于Client类的内容:

客户端实例是昂贵的资源。建议重用已配置的实例来创建 Web 资源。Web 资源的创建、请求的构建和响应的接收都保证是线程安全的。因此,一个 Client 实例和 WebResource 实例可以在多个线程之间共享

因此,如果您计划进行多次调用,最好不要为每个调用调用 destroy。WebResources 也是如此(但程度较轻)。

3)我所描述的来自 Jersey 1.1(但我早在 2009 年就看到了关于此的主题)。

于 2012-06-21T11:43:08.023 回答