因为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")
}
}
原文地址:http://blog.51cto.com/8953871/2125901