【问题标题】:Using streaming HTTP chunked responses in Playframework在 Playframework 中使用流式 HTTP 分块响应
【发布时间】:2018-08-14 14:58:08
【问题描述】:

我正在尝试使用 Play 框架 2.6 在 Java 中构建一个 REST API,它将以块的形式向客户端发送响应。为此,我按照播放 HTTP 响应流的documentation 遵循分块响应构建器示例。

在示例中(也在下面复制),发送块后,它正在关闭源。如何在一些处理后保持源打开并使用 sourceActor 继续发送更多消息?这个处理可能发生在其他可以访问 sourceActor 的 Actor 中。

public Result index() {
// Prepare a chunked text stream
Source<ByteString, ?> source = Source.<ByteString>actorRef(256, OverflowStrategy.dropNew())
    .mapMaterializedValue(sourceActor -> {
        sourceActor.tell(ByteString.fromString("kiki"), null);
        sourceActor.tell(ByteString.fromString("foo"), null);
        sourceActor.tell(ByteString.fromString("bar"), null);
        sourceActor.tell(new Status.Success(NotUsed.getInstance()), null);
        return NotUsed.getInstance();
    });
// Serves this stream with 200 OK
return ok().chunked(source);
}

【问题讨论】:

    标签: java playframework akka akka-stream playframework-2.6


    【解决方案1】:

    使用BroadcastHub:

    Pair<ActorRef, Source<ByteString, NotUsed>> source =
      Source.<ByteString>actorRef(256, OverflowStrategy.dropNew())
        .toMat(BroadcastHub.of(ByteString.class), Keep.both())
        .run(materializer);
    
    ActorRef sourceActor = source.first();
    Source<ByteString, NotUsed> matSource = source.second();
    

    发送到物化actor的消息被发送到下游,你可以使用物化源来完成方法(注意这种方法没有背压):

    sourceActor.tell(ByteString.fromString("kiki"), ActorRef.noSender());
    // send more messages to sourceActor...
    
    return ok().chunked(matSource);
    

    您可能需要使用keepAlive 将消息注入流中以使其保持打开状态。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2016-01-12
      • 2012-04-02
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      相关资源
      最近更新 更多