消息转到死信而不是发件人(akka路由器)[scala]

时间:2014-09-26 19:18:50

标签: akka router actor dead-letter scaldi

实际上我在让我的演员(路由器)系统正常工作方面遇到了麻烦。 我的设置:

我试图在播放控制器中使用akka路由器。对于依赖注入,我使用scaldi。

scaldi模块:

class UserDAOModule extends Module {
  binding to new ExampleRouter
  binding toProvider new UserDAOWorker
}

akka router:

class UserDAORouter(implicit inj:Injector) extends Actor with AkkaInjectable {

  val userDAOProps = injectActorProps[UserDAOWorker]

  var router = {
    val routees = Vector.fill(5) {
      val r = context.actorOf(userDAOProps)
      context watch r
      ActorRefRoutee(r)
    }
    Router(RoundRobinRoutingLogic(), routees)
  }

  override def receive: Receive = {
    case mm: MongoDBMessage =>
      router.route(mm, sender)
    case Terminated(a) =>
      router = router.removeRoutee(a)
      val r = context.actorOf(userDAOProps)
      context watch r
      router = router.addRoutee(r)
  }

}

工人:

class UserDAOWorker(implicit inj:Injector) extends Actor with Injectable {

  val db = inject[DefaultDB]
  val collection:JSONCollection = db("users")
  val currentSender = sender

  override def receive: Receive = {
    case InsertUser(user) => insertUser(user)
  }

  def insertUser(user:User) = {
    collection.save(user).onComplete {
      case Failure(e) => currentSender ! new UserDAOReturnMessage(Some(e), None)
      case Success(lastError) => currentSender ! new UserDAOReturnMessage(None, lastError)
    }
  }
}

当我向路由器发送消息(insertUser消息)时,它被正确路由并且工作人员收到消息,但是当工作人员向发送者发送消息时,它无法发送,因此它被发送到死信办公室。我无法弄清楚如何解决这个问题。有人能帮助我吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

我想问题是在actor创建的构造函数中,currentSender被初始化为null(即ActorRef.noSender)。 'sender'仅在receive()中接收消息的上下文中有效。向ActorRef.noSender发送消息相当于发送到死信队列。

这样的事情应该有效:

class UserDAOWorker(implicit inj:Injector) extends Actor with Injectable {

  val db = inject[DefaultDB]
  val collection:JSONCollection = db("users")

  override def receive: Receive = {
    case InsertUser(user) => {
      insertUser(sender, user)
    }
  }

  def insertUser(currentSender : ActorRef, user:User) = {
    collection.save(user).onComplete {
      case Failure(e) => currentSender ! new UserDAOReturnMessage(Some(e), None)
      case Success(lastError) => currentSender ! new UserDAOReturnMessage(None, lastError)
    }
  }
}