Scala:文件数据的顺序处理



我有一个csv文件,我从中读取数据并填充我的数据库。我正在使用 scala 来做到这一点。与其以并行方式触发 db 插入,不如以顺序方式(即一个接一个)执行插入。我不愿意在 for 循环中使用 Await。除了使用 await 之外,还有其他方法吗?

PS:我已经将 csv 中的 1000 个条目读取到列表中,并在列表上循环以创建数据库插入

假设你的数据库有某种save(entity: T): Future[_]方法,你可以用flatMap(或为了理解)折叠你的期货:

def saveAll(entities: List[T]): Future[Unit] 
entities.foldLeft(Future.successful(())){
case (f, entity) => for {
_ <- f
_ <- save(entity)
} yield ()
}
}

另一种选择是递归函数。 不如foldLeft简洁,但对某些人来说更具可读性。 还有一个选项供您考虑(假设save(entity: T): Future[R]

def saveAll(entities: List[T]): Future[List[R]] = {
entities.headOption match {
case Some(entity) => 
for {
head <- save(entity)
tail <- saveAll(entities.tail)
} yield {
head :: tail
}
case None =>
Future.successful(Nil)
}
}

另一种选择,如果您的save方法允许您提供自己的ExecutionContextsave(entity: T)(implicit ec: ExecutionContext): Future[R],只是同时触发Future,但使用单线程执行上下文:

def saveAll(entities: List[T]): Future[List[R]] = {
implicit ec = ExecutionContext.fromExecutionService(java.util.concurrent.Executors.newSingleThreadExecutor)
Future.sequence(entities.map(save))
}

最新更新