ACTOR中不允许出现阻塞

   因为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")
               }
     }

猜你喜欢

转载自blog.51cto.com/8953871/2125901