如何在akka进行监督

时间:2015-08-18 14:23:43

标签: scala exception exception-handling akka akka-supervision

我有两个演员,一个是父级,一个是小孩,子actor负责从MongoDB中获取给定id的数据,并将数据回复给调用actor,在我的情况下是父节点,现在我想要在我的孩子演员应用监督我知道如何执行监督策略,但如何在我的代码中这样做让我感到困惑 我在我的try / catch块中捕获异常,这样每种类型的异常都会被捕获,但后来我被困在了如何app,y监督,因为我不知道我的代码将来会抛出什么异常我的代码请帮帮我 ReadOnlyAdminQueryActor.scala(专利演员)

class ReadOnlyAdminQueryActor extends Actor{

val log = LoggerFactory.getLogger("controller")
     case ReadOnlyAdminReadByID(idList)=>
          var RetunedLists = new MutableList[ReadOnlyAdmin]()
          RetunedLists=  readById(idList)
          sender ! RetunedLists //return list of ReadOnlyAdmin objects to the calling actor (matched uuid results)
   def readById(idList:MutableList[Int]):MutableList[ReadOnlyAdmin]= {
    var connection=MongoFactory.getConnection
    var collection=MongoFactory.getCollection(connection, "readOnlyAdmin")

   var RetunedList = new MutableList[ReadOnlyAdmin]()

    var id:Int=0
    var email:String=""
    var SecondryEmail:Option[String]=None
    var FirstName:String=""
    var LastName:String=""
    var userStatus:String=""

  log.info("readOnlyAdmin query class data method readByID")

 for(Id<-idList){

    val q=QueryBuilder.start("_id").is(Id)

    val cursor=collection.find(q.get)
    var obj=new BasicDBObject

 try {
     while(cursor.hasNext)
     {
       obj=cursor.next().asInstanceOf[BasicDBObject]

       id=obj.getString("_id").toInt
       email=obj.getString("Email")
       SecondryEmail=Option(obj.getString("SecondryEmail"))
       FirstName=obj.getString("FirstName")
       LastName=obj.getString("LastName")
       userStatus=obj.getString("UserStatus")

       val readOnlyAdmin=new ReadOnlyAdmin(id,FirstName, LastName, email, SecondryEmail ,"",UserStatus.withName(userStatus))
       RetunedList+=readOnlyAdmin  //adding objects in a list


     }//end of while
   }//end of try
    catch
    {
      case e: Exception => log.error("printStackTrace"+e.printStackTrace)

    }
   finally{
     cursor.close()
     MongoFactory.closeConnection(connection)

   }
 }//end for loop

    RetunedList
 }
}

ReadOnlyAdminReadMongoActor.scala(儿童演员)

    class ReadOnlyAdminReadMongoActor extends Actor{
      val log = LoggerFactory.getLogger("controller")
      val ReadOnlyAdminQueryActor=context.actorOf(Props[ReadOnlyAdminQueryActor].withDispatcher("akka.actor.readOnlyAdminReadMongoActor-dispatcher"), name = "ReadOnlyAdminQueryActor")

    case ReadOnlyAdminReadFromMongoById(readOnlyAdmin,idList)=>
            var RetunedLists = new MutableList[ReadOnlyAdmin]()
            implicit val timeout = Timeout(10 seconds)//wait for 10 seconds 
override val supervisorStrategy: SupervisorStrategy = {
    OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 10 seconds) {
      case x: Exception => ???
    }
  }

             val future:Future[MutableList[ReadOnlyAdmin]] = ask(ReadOnlyAdminQueryActor,ReadOnlyAdminReadByID(idList)).mapTo[MutableList[ReadOnlyAdmin]] 
             future.onComplete { 
              case Success(result)=>
                RetunedLists=result
                      for(a<-RetunedLists)
                      {
                           log.info ("id is "+a.getUuid+"First name is "+a.getFirstName
                          +"Last name is "+a.getLastName+"Email is "+a.getEmail 
                          +"secondry email is "+a.getSecondryEmail+"user status is "+a.getUserStatus)
            }

             case Failure(e)=>
             log.error(" in failure")
             log.error("printStackTrace"+e.printStackTrace)
    }

object Test extends App{
 val system = ActorSystem("TestSystem")
val readOnlyAdmin= new ReadOnlyAdmin
var uuidsList = new MutableList[Int]()
uuidsList+=123
val ReadOnlyAdminReadMongoActor=system.actorOf(Props[ReadOnlyAdminReadMongoActor].withDispatcher("akka.actor.readOnlyAdminReadMongoActor-dispatcher"), name = "ReadOnlyAdminReadMongoActor")
ReadOnlyAdminReadMongoActor ! ReadOnlyAdminReadFromMongoById(readOnlyAdmin,uuidsList)       

}

我如何以正确的方式执行监督?我如何知道将在我的孩子演员中抛出哪个异常还幸运的是,Java库明确说明了他们将要抛出的内容,而Scala库几乎总是抛出非常即使在IDE中很少或没有,当我们将鼠标悬停在代码上时,不会显示任何信息 请提前帮助我

1 个答案:

答案 0 :(得分:1)

主管策略属于Parent,而不是Child。孩子应该抛出异常,父母决定如何处理失败。在下面的代码中,Child actor将重启3次,然后终止:

class Parent extends Actor {

    override def preStart(): Unit = {
      self ! "Start Child"
    }

   def receive = {
     case "Start Child" => context.actorOf(Props[Child])
   }

  override def supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 3) {
    case ex: Throwable => Restart
  }
}

class Child extends Actor {

  override def preStart() = {
    self ! "Throw"
  }

  def receive = {
    case "Throw" => throw new Exception("Throwing")
  }
}