因爲actor接收請求的速度很快,如果出現阻塞(如IO操作)會耗時,接收請求的速度超過程
序處理的速度就可能會導致內存溢出。如果中間需要連接數據庫 的話,數據庫操作需要在Future
中進行,然後爲Future分配線程池, 來保證數據庫的操作無阻塞進行。
例如定義一個接口
trait IAsyncDB{
protected val executionContext: ExecutionContextExecutor = ExecutionContext.fromExecutor(new ForkJoinPool(128))
/**
* 異步執行dao方法
*
* @param body dao的方法
* @tparam T 返回類型
* @return
*/
def async[T](body: => T): Future[T] = Future(body)(executionContext)
}
然後在有數據庫操作的類中繼承這個接口,數據庫操作調用async方法:
class UserService(userDao:UserDao) extends Actor with IAsyncDB{
override def receive: Receive = {
case "find" => async(userDao.find)
case "other"=> println("hahahahaha")
}
}
ACTOR中不允許出現阻塞
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.