因为 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://www.bubuko.com/infodetail-2634681.html