gpt4 book ai didi

java - 关闭 JAX RS 客户端/响应

转载 作者:行者123 更新时间:2023-12-04 12:40:13 25 4
gpt4 key购买 nike

不清楚我是否必须关闭 JAX RS 客户端/响应实例。如果我必须,总是还是不?
根据 documentation关于 Client 类:

Calling this method effectively invalidates all resource targetsproduced by the client instance.


WebTarget 类没有任何 invalidate()/close() 方法,但 Response 类有。
根据 documentation :

Close the underlying message entity input stream (if available andopen) as well as releases any other resources associated with theresponse (e.g. buffered message entity data).

... The close() methodshould be invoked on all instances that contain an un-consumed entityinput stream to ensure the resources associated with the instance areproperly cleaned-up and prevent potential memory leaks. This istypical for client-side scenarios where application layer codeprocesses only the response headers and ignores the response entity.


最后一段我不清楚。 “未消费的实体输入流”是什么意思?如果我从响应中得到 InputSteam 或 String,我应该明确关闭响应吗?
我们可以在不访问 Response 实例的情况下获得响应结果:
Client client = ...;
WebTarget webTarget = ...;
Invocation.Builder builder = webTarget.request(MediaType.APPLICATION_JSON_TYPE);
Invocation invocation = builder.buildGet();
InputStream reso = invocation.invoke(InputStream.class);
我正在使用 RESTeasy 实现,我预计响应将在 resteasy 实现内关闭,但我找不到它。谁能告诉我为什么?
我知道 the Response class will implement Closeable interface
但即使知道, Response 被使用,没有关闭它。

最佳答案

根据文档 close() 是幂等的。

This operation is idempotent, i.e. it can be invoked multiple times with the same effect which also means that calling the close() method on an already closed message instance is legal and has no further effect.



这样您就可以安全地关闭 InputStream你自己和应该。

话虽如此,我的风格明智不会做 invocation.invoke(InputStream.class)invoker(Class)用于进行实体转换。相反,如果你想要 InputStream,你应该只调用 invocation.invoke()并处理 Response直接对象,因为在读取流之前您可能需要一些标题信息。
处理响应时需要 header 的原因 InputStream是典型的,因为您要么不关心主体,要么主体需要特殊的处理和大小考虑,这就是文档所暗示的(例如 HEAD 请求 ping 服务器)。

另见 link

A message instance returned from this method will be cached for subsequent retrievals via getEntity(). Unless the supplied entity type is an input stream, this method automatically closes the an unconsumed original response entity data stream if open. In case the entity data has been buffered, the buffer will be reset prior consuming the buffered data to enable subsequent invocations of readEntity(...) methods on this response.



因此,如果您选择 InputStream 以外的任何内容您不必关闭 Response (但不管它是安全的,因为它是幂等的)。

关于java - 关闭 JAX RS 客户端/响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33083961/

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