我正在創建一個服務,該服務運行一個單詞列表,併爲每個單詞檢查數據庫中是否存在相關操作(執行)。使用未來進行併發搜索和結果返回
我正在嘗試使用Futures同時執行此操作,而且我不確定是否使用最佳方式。
```
class CommandDiscoveryService (commandsDAO: CommandsDAO, text: String) {
val words = text.split("\\s+")
var results = new ListBuffer[Option[Execution]]()
// Temporarily handle with concurrent searchs on the database
// TODO Load all commands to memory and check the list ?? memcache or some other cache service
if (words.size <= 6) {
Logger.debug("Searching for executions with text " + text)
findExecution()
}
def findExecution() = {
val lb = new ListBuffer[Future[Seq[Execution]]]()
for (word <- words) {
lb += commandsDAO.findExecutionByName(word)
}
lb.foreach(Await.result(_, 1 seconds))
import scala.concurrent.ExecutionContext.Implicits.global // FIXME LATER
val res = lb.map {
ftr => ftr.map{
res => {
if (res.size > 0) {
Logger.debug("RES SIZE:" + res.size)
res.map{ ex => results += Some(ex) }
}
}
}
}
}
def getExecution(): Option[Execution] = {
if (results.size > 1) {
Logger.debug("ERROR_TOMANYEXECS: Found more than one execution " + results.head)
results.foreach{
execs => Logger.debug("ERROR_TOMANYEXECS: " + execs)
}
None
} else {
if (results.size == 0) {
Logger.debug("NOTHING FOUND IN RES")
None
} else {
Logger.debug("FOUND RES " + results.head)
results.head
}
}
}
}
```
當我打電話getExecution我需要已經得到完成的搜索的價值。我不確定是否對這個結果變量進行鎖定將會成爲等待未來的解決方案[Seq [Execution]]已經不被推薦。 PS:我使用playframework 2.6.x和Slick來運行它。
編號Await.result阻塞,因此它不好 –
但我需要等待結果。 –