2016-12-24 28 views
0

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

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

看看这个https://dzone.com/articles/jerseyjax-rs-streaming-json – gladiator

回答

1

你需要的是输出缓冲区内容长度设置为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运行我的上述代码将每100ms产生一行“hello”。使用卷曲我可以看到所有输出立即打印。

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

+0

谢谢你解决了我的问题! – user1807948

相关问题