gpt4 book ai didi

jax-rs - jax-rs 用例中的 StreamingOutput?

转载 作者:行者123 更新时间:2023-12-04 01:52:46 32 4
gpt4 key购买 nike

JAX-RS 提供了 StreamingOutput 接口(interface),我们可以实现它来对我们的响应主体进行原始流处理。

public interface StreamingOutput {
void write(OutputStream output)
}

我不确定他们为什么要构建一个接口(interface)来公开响应输出流。为什么不直接注入(inject)一个 OutputStream,我们就可以简单地在上面写入!!

最佳答案

在书中RESTful Java with JAX-RS 2.0由 Bill Burk(RESTEasy 作者之一)撰写,您会找到关于 StreamingOutput 的很好的解释。

作者回答了你问的同样问题:

StreamingOutput is a simple callback interface that you implement when you want to do raw streaming of response bodies [...]

You allocate implemented instances of this interface and return them from your JAX-RS resource methods. When the JAX-RS runtime is ready to write the response body of the message, the write() method is invoked on the StreamingOutput instance. [...]

You may be asking yourself, “Why not just inject an OutputStream directly? Why have a callback object to do streaming output?” That’s a good question! The reason for having a callback object is that it gives the JAX-RS implementation freedom to handle output however it wants. For performance reasons, it may sometimes be beneficial for the JAX-RS implementation to use a different thread other than the calling thread to output responses. More importantly, many JAX-RS implementations have an interceptor model that abstracts things out like automatic GZIP encoding or response caching. Streaming directly can usually bypass these architectural constructs. Finally, the Servlet 3.0 specification has introduced the idea of asynchronous responses. The callback model fits in very nicely with the idea of asynchronous HTTP within the Servlet 3.0 specification.

StreamingOutput documentation陈述如下:

This is a lightweight alternative to a MessageBodyWriter.

关于jax-rs - jax-rs 用例中的 StreamingOutput?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38632895/

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