2016-12-24 3 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ごとに1つの行「hello」が生成されます。カールを使用すると、すべての出力がすぐに印刷されることがわかります。

OUTBOUND_CONTENT_LENGTH_BUFFERを設定することの副作用と、望ましくない副作用を導入していないことを確認する必要があります。

+0

ありがとう、私の問題を解決しました! – user1807948

関連する問題