gpt4 book ai didi

java - 如何通过 Jersey 响应对象同时传输 OutputStream

转载 作者:行者123 更新时间:2023-11-30 02:42:12 25 4
gpt4 key购买 nike

我正在尝试通过响应对象流式传输 ProcessBuilder 的输出。现在,只有在该过程完成后,我才能在客户端获得输出。我希望看到客户端的输出同时被打印。目前这是我的代码,它在进程完成后打印出客户端(POSTMAN)中的所有内容。

 StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
String line;
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
while ((line = input.readLine()) != null) {
writer.write("TEST");
writer.write(line);
writer.flush();
os.flush();;
}
} finally {
os.close();
writer.close();
}
}
};
return Response.ok(stream).build();

最佳答案

您需要的是将输出缓冲区内容长度设置为 0,以便 jersey 不缓冲任何内容。有关更多详细信息,请参阅此:calling flush() on Jersey StreamingOutput has no effect

这是一个 Dropwizard 独立应用程序,演示了这一点:

public class ApplicationReddis extends io.dropwizard.Application<Configuration>{

@Override
public void initialize(Bootstrap<Configuration> bootstrap) {
super.initialize(bootstrap);
}

@Override
public void run(Configuration configuration, Environment environment) throws Exception {
environment.jersey().property(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0);
environment.jersey().register(StreamResource.class);
}

public static void main(String[] args) throws Exception {
new ApplicationReddis().run("server", "/home/artur/dev/repo/sandbox/src/main/resources/config/test.yaml");
}

@Path("test")
public static class StreamResource{

@GET
public Response get() {
return Response.ok(new StreamingOutput() {

@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
for(int i = 0; i < 100; i++) {
output.write(("Hello " + i + "\n").getBytes());
output.flush();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).build();
}
}

}

别介意 Dropwizard 部分,它只是在引擎盖下使用 Jersey 。

environment.jersey().property(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0);

这部分将出站长度设置为 0。这将导致 jersey 不缓冲任何内容。

您仍然需要刷新 StreamingOutput 中的输出流,因为该输出流有自己的缓冲区。

使用 Dropwizard 1.0.2 运行上面的代码将每 100 毫秒生成一行“hello”。使用curl我可以看到所有输出都立即打印出来。

您应该阅读文档和设置OUTBOUND_CONTENT_LENGTH_BUFFER的副作用,以确保不会引入不需要的副作用。

关于java - 如何通过 Jersey 响应对象同时传输 OutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41311372/

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