【问题标题】:Mess with async function with two threads in Play app在 Play 应用程序中使用两个线程混淆异步功能
【发布时间】:2016-06-21 14:30:15
【问题描述】:

我正在构建一个假设构建 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)

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

[错误] services.data.model.ChecklistSchema$Schema 无法转换 到 scala.Option (ChecklistResultsExportService.scala:38) [错误] services.data.ChecklistResultsExportService$$anonfun$buildCsv$1.apply(ChecklistResultsExportService.scala:38)

第 38 行是这样的:

schemaFuture flatMap { optSchema

我错过了什么?

谢谢。

【问题讨论】:

    标签: multithreading scala playframework future


    【解决方案1】:

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

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

    现在似乎可以工作了。

    谢谢。

    【讨论】:

      猜你喜欢
      • 2017-09-14
      • 2014-05-04
      • 1970-01-01
      • 2019-04-25
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-06
      相关资源
      最近更新 更多