从Play2.5.x开始,Play使用Akka Streams实现流处理,废弃了以前的Enumerator/Iteratee Api。根据官方文档描述,迁移至Akka Streams以后,Play2.5.x的总体性能提高了20%,性能提高至关可观。虽然官方已经更新了JavaStream的文档,可是ScalaStream的文档仍然没有更新,已经提了issue,但愿能尽快获得反馈。 ReactiveMongo是一个基于Scala开发的彻底异步非阻塞、而且提供流处理功能的MongoDB驱动。该项目目前的流处理功能基于Enumerator/Iteratee实现,Akka Stream的实现放在一个单独的项目开发(RM-AkkaStreams)。 结合Play和ReactiveMongo两者的流处理功能,咱们能够很方便地实现彻底异步非阻塞的报表导出功能。react
因为ReactiveMongo暂时尚未提供Akka Streams的流处理实现,因此没法直接经过map/flatMap直接返回一个Stream写回响应:git
@Singleton class TestStreamController @Inject()(val reactiveMongoApi: ReactiveMongoApi, implicit val mat: Materializer) extends Controller { def qaCol: JSONCollection = reactiveMongoApi.db.collection[JSONCollection]("qa") def exportDataStream = Action { implicit request => val source = Source.actorRef[ByteString](10000, OverflowStrategy.fail).mapMaterializedValue { sourceActor => qaCol .find(Json.obj()) .options(QueryOpts(batchSizeN = 1000)) .cursor[QA]() .foldBulks[Int](0){ (index, list) => sourceActor ! ByteString(list.map(qa => qa.question).mkString("\n") + "\n") Cursor.Cont(index + 1) } .map{ _ => sourceActor ! akka.actor.Status.Success(()) } } Ok.chunked(source) .withHeaders( "Content-Type" -> "application/octet-stream", "Content-Disposition" -> (s"attachment;filename=export-" + new DateTime().toString("yyyy-MM-dd") + ".txt")) } }
代码第5行Source.actorRef
函数启动一个actor实例sourceActor
负责收集报表数据,Source.actorRef
的第1个参数bufferSize
用于指定缓冲区大小,即Play来不及写回响应的数据暂时放在缓冲区,第2个参数overflowStrategy
指定缓冲区溢出后的处理策略。 第10行foldBulks
方法负责批量从MongoDB数据库读取查询结果,而后以消息形式将数据发送给sourceActor
,最后发送一个Status.Success
消息代表数据已经发送完毕。 数据传递过程以下:github
foldBulks(读取查询结果) -> sourceActor(收集查询结果) -> source(生产者) -> Ok.chunked(消费者)
下面是浏览器中看到的效果:数据库
图中499KB/s
表示当前的下载速度,997KB
表示当前累计的下载大小。浏览器