使用jersey的JAX RS的内存问题
我们目前在高效的服务器上遇到了一些麻烦,因为它消耗的内存过多.其中一个漏洞可能来自球衣客户端.我发现了以下两个问题以及如何:
> How to correctly share JAX-RS 2.0 client 我从中获得了什么,我应该重用客户端,还可能重用WebTargets? 代码示例,使用不同的路径每小时调用大约1000次: public byte[] getDocument(String path) { Client client = ClientBuilder.newClient(); WebTarget target = client.target(config.getPublishHost() + path); try { byte[] bytes = target.request().get(byte[].class); LOGGER.debug("Document size in bytes: " + bytes.length); return bytes; } catch (ProcessingException e) { LOGGER.error(Constants.PROCESSING_ERROR,e); throw new FailureException(Constants.PROCESSING_ERROR,e); } catch (WebApplicationException e) { LOGGER.error(Constants.RESPONSE_ERROR,e); throw new FailureException(Constants.RESPONSE_ERROR,e); } finally { client.close(); } } 所以我的问题是如何正确使用API??来防止上述示例的泄漏? 解决方法
应重用客户端实例
documentation建议只创建少量的 WebTarget实例可以重用 如果对同一路径执行多个请求,则可以重用 如果您不读取实体,则应关闭响应实例 应关闭包含未消耗实体输入流的 改善您的代码 对于您的问题中提到的情况,您希望确保将 例如,如果您的应用程序是基于CDI的,则在构造bean时创建一个 @Singleton public class MyBean { private Client client; @PostConstruct public void onCreate() { this.client = ClientBuilder.newClient(); } ... @PreDestroy public void onDestroy() { this.client.close(); } } 您不需要(或者可能不能)重用 使用连接池 连接池可以很好地提高性能. 正如我早期的answer中所提到的,默认情况下,Jersey中的传输层由 Jersey通过 <dependency> <groupId>org.glassfish.jersey.connectors</groupId> <artifactId>jersey-apache-connector</artifactId> <version>2.26</version> </dependency> 然后按如下方式创建您的 PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(100); connectionManager.setDefaultMaxPerRoute(5); ClientConfig clientConfig = new ClientConfig(); clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER,connectionManager); clientConfig.connectorProvider(new ApacheConnectorProvider()); Client client = ClientBuilder.newClient(clientConfig); 有关其他详细信息,请参阅Jersey documentation about connectors. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |