我正在尝试通过response对象流ProcessBuilder的输出。现在,只有在流程完成之后,我才能在客户端获得输出。我希望客户端的输出同时被打印出来。目前,这是我的代码,它打印在客户端(邮递员)完成后的一切。
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();发布于 2016-12-29 12:19:42
您需要的是将输出缓冲区内容长度设置为0,这样泽西就不会缓冲任何内容。有关更多细节,请参见此: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部分,它只是使用引擎盖下的球衣。
environment.jersey().property(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0);此部分将出站长度设置为0。这将导致球衣不缓冲任何东西。
您仍然需要在StreamingOutput中刷新输出流,因为它有自己的缓冲区。
使用Dropwizard 1.0.2运行上述代码,每100 my将生成一行"hello“。使用curl,我可以看到所有输出都是立即打印的。
您应该阅读设置OUTBOUND_CONTENT_LENGTH_BUFFER的文档和副作用,以确保您没有引入不必要的副作用。
https://stackoverflow.com/questions/41311372
复制相似问题