2016-12-24 24 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

相關問題