在 Play 应用程序中使用两个线程处理异步函数

Mess with async function with two threads in Play app

我正在构建一个假设要构建 CSV 文件的服务方法。文件的标题和结果来自不同的线程。

def buildCsv(template: Template) : Future[TemporaryFile] = {

        val schemaFuture = dbViewSchemaRepository.findOneByTemplateId(template.id)
        val resultsFuture = checklistResultRepository.findAllByTemplateId(template.id)

        schemaFuture flatMap { optSchema =>
            val schema = optSchema match {
                case Some(sch : Schema) => sch
                case _ => throw UnexpectedException("Schema not found")
            }

            //get the titles
            val titles = buildTitles(schema)
            // create temp file
            val tempFile = TemporaryFile("test", ".csv")
            logger.info("Absolute path: " + tempFile.file.getAbsolutePath)

            // start writing results
            resultsFuture map { results =>
                results foreach { result =>
                    val resultRow = buildResultRow(result, schema)

                    tempFile.file.writeCsv(List(resultRow), ',', titles)
                }

                tempFile
            }

        }
    }

我构建了一个非常简单的测试:

var dbViewSchemaRepo = mock[DbViewSchemaRepository]
            doReturn(Future(schema)).when(dbViewSchemaRepo).findOneByTemplateId(schema.templateId)

            var checklistResultRepo = mock[ChecklistResultRepository]
            doReturn(Future(List(result))).when(checklistResultRepo).findAllByTemplateId(schema.templateId)

            val template = mock[Template]
            template.id returns schema.templateId

            var srv = new ChecklistResultsExportService(dbViewSchemaRepo, checklistResultRepo)

当我 运行 它时,我得到一个错误:

[error] services.data.model.ChecklistSchema$Schema cannot be cast to scala.Option (ChecklistResultsExportService.scala:38) [error] services.data.ChecklistResultsExportService$$anonfun$buildCsv.apply(ChecklistResultsExportService.scala:38)

第 38 行是这样的:

schemaFuture flatMap { optSchema

我错过了什么?

谢谢。

我的问题是我模拟来自存储库对象的响应的方式。我应该这样做:

doReturn(Future.successful(Some(schema))).when(dbViewSchemaRepo).findOneByTemplateId(schema.templateId)     
   doReturn(Future.successful(List(result))).when(checklistResultRepo).findAllByTemplateId(schema.templateId)

现在似乎在工作。

谢谢。