我正在尝试通过响应对象传输processbuilder的ouput。现在,我只有在完成过程完成后才获得客户端的输出。我希望看到客户端的输出同时打印。目前,这是我的代码,并且在完成该过程后会打印出客户端(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,以使泽西不会缓冲任何东西。有关更多详细信息,请参阅此信息:泽西式流式点上的呼叫flush()没有效果
这是一个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部分,它只是在引擎盖下使用泽西岛。
environment.jersey().property(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0);
此部分将出站长度设置为0。这将导致球衣不缓冲任何东西。
您仍然需要在流媒体输出中冲洗输出流,因为那个具有自己的缓冲区。
使用Dropwizard 1.0.2运行上述代码,每100ms将产生一行" Hello"。使用卷发,我可以看到所有输出都立即打印出来。
您应该阅读文档和设置OUTBOUND_CONTENT_LENGTH_BUFFER
的副作用,以确保您不会引入不必要的副作用。