因为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中不允许出现阻塞
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.