Tôi đã đọc một vài hướng dẫn về làm thế nào để đối phó với đồng thời trong Play và tìm thấy một số ví dụ:Concurrency in Chơi 2.1 hoặc cao hơn
Asynchronous Job
import scala.concurrent.{ExecutionContext, future}
def sendEmailAsync(from: String, to: String, subject: String, body: String) = {
import ExecutionContext.Implicits.global // in scala.concurrent
future {
EmailHelper.sendEmail(from, to, subject, body)
}
}
Theo lịch trình công việc
import play.api.libs.concurrent.{Akka, Execution}
def sendEmailOnSchedule(from: String, to: String, subject: String, body: String) = {
import scala.concurrent.duration._
import Execution.Implicits.defaultContext // in play.api.libs.concurrent
Akka.system.scheduler.scheduleOnce(10 seconds) {
EmailHelper.sendEmail(from, to, subject, body)
}
}
Vâng, tôi hơi bối rối ... ví dụ đầu tiên sử dụng scala.concurrent.ExecutionContext.Implicits.global
trong khi ví dụ thứ hai sử dụng play.api.libs.concurrent.Execution.Implicits.defaultContext
. Tại sao? Ai đó có thể giải thích cho tôi những gì đang xảy ra đằng sau hiện trường?
'ExecutingContext' giống như ExecutorService của java (Thread Pool), bạn thậm chí có thể tự tạo nó nếu bạn muốn. Ví dụ, mô-đun play-slick sử dụng một bối cảnh riêng biệt để thực hiện các hoạt động db. https://github.com/freekh/play-slick/blob/master/src/main/scala/play/api/db/slick/SlickExecutionContext.scala – jilen