我有一個用例,涉及分 3 個步驟處理檔案上傳:
- 在資料庫中創建條目
- 使用先前的 id 從檔案中提取元資料并存盤在資料庫中
- 將檔案存盤在云檔案夾中
我希望第 2 步發生在火災和忘記的方式,但它需要來自第 1 步的 id。我希望第 1 步和第 3 步同步發生并盡快回傳。我的代碼看起來像:
def storeFile(): Future[Long]
def extractAndSaveMetadata(id:Long, content:Bytestring) : Future[Unit]
def storeFile(id, Long, content:ByteString): Future[Unit]
for {
id <- createEntryInDB()
_ <- extractAndSaveMetadata(id, content)
_ <- storeFile(id, content)
} yield ()
這種方法的問題在于第 2 步非常慢,并且使其最終一致沒有問題。同時,它需要第 1 步中的值,所以我不知道如何在這個 monadic 呼叫序列中取消執行緒并忘記呼叫。
有沒有辦法在 Future for-comprehension 中“分叉”未來的執行?
uj5u.com熱心網友回復:
是的,解決方案是@SwiftMango 指出的。代碼翻譯成:
for {
id <- createEntryInDB()
_ = extractAndSaveMetadata(id, content)
_ <- storeFile(id, content)
} yield ()
評論中的其他建議方法不起作用,因為:
- 我不想在之后回傳
extractAndSaveMetadata或storeField回傳。只有 1 條主要路徑是createEntry andThen storeFile - 它確實是一系列任務,沒有第一個任務中的 id 就不能運行 2 和 3。
- 使用
Future.sequence將阻止整個執行緒上游,直到所有期貨完成。我想盡快歸還控制權。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/384765.html
