跟进此问题:Play Framework 2.5 Streaming content with delay
我一直在尝试通过Akka Streams和Play Framework从MongoDB Reactive流式传输数据。问题在于,由于某种原因,数据首先收集,然后发送完整的集合,而不是单独流式传输每个项目。
Mongo驱动程序代码:
public FindPublisher<Document> findAll(){
FindPublisher iterator = collection.find();
return iterator;
}
从Mongo Publisher映射到源
public Source<Rating, NotUsed> findAll(){
return Source.fromPublisher(mongoConnection.findAll()).map(doc -> new Rating().fromDocument(doc));
}
从Play Framework控制器返回
public Result findAll(){
Source<Rating, NotUsed> ratingsStream = ratingRepository.findAll();
Source<ByteString, NotUsed> byteStringStream = ratingsStream
.map(rating -> ByteString.fromString(rating.toDocument().toJson() + "\n"))
.delay(FiniteDuration.create(100, TimeUnit.MILLISECONDS), DelayOverflowStrategy.backpressure());
HttpEntity.Streamed streamed =
new HttpEntity.Streamed(byteStringStream, Optional.empty(), Optional.of("text/event-stream"));
return ok().sendEntity(streamed);
}
这里的延迟只会延迟整个流(如initialDelay()),然后返回整个Mongo数据。
根据我之前提出的问题,此方法在创建新来源时有效:
public Result test(){
Source<ByteString, NotUsed> delay = Source.range(0, 99999)
.map(i -> ByteString.fromString(i.toString() + "\n"))
.delay(FiniteDuration.create(200, TimeUnit.MILLISECONDS), DelayOverflowStrategy.backpressure());
HttpEntity http = new HttpEntity.Streamed(delay
, Optional.empty(), Optional.of("text/event-stream"));
return ok().sendEntity(http);
}
我检查了数据,项目确实单独发出。起初我以为Mongo可能会返回整个集合而不是流式传输,但事实并非如此。映射每个项目是否有效,因此延迟它们也应该起作用?
我只能认为这与fromPublisher(Publisher<T>)
静态方法有关。
我使用Play Framework 2.5,MongoDB Driver Reactive 1.3.0和Akka 2.5.2
感谢任何帮助!