Akka and ReactiveMongo

怎甘沉沦 提交于 2019-12-02 21:06:04

I would create the driver and connection in the master actor. I would then set up the the worker actors to take an instance of MongoConnection as a constructor argument so that each worker has a reference to the connection (which is really a proxy to a pool of connections). Then, in something like preStart, have the master actor create the workers (which I am assuming are routed) and supply the connection as an arg. A very simplified example could look like this:

class MongoMaster extends Actor{
  val driver = new MongoDriver
  val connection = driver.connection(List("localhost"))

  override def preStart = {
    context.actorOf(Props(classOf[MongoWorker], connection).withRouter(FromConfig()))
  } 

  def receive = {
    //do whatever you need here
    ...
  }
}

class MongoWorker(conn:MongoConnection) extends Actor{
  def receive = {
    ...
  }
}

This code is not exact, but at least it shows the high level concepts I described.

The answer by cmbaxter works as long as you don't need to instantiate the worker actors remotely. MongoConnection is not serializable.

I found this article https://github.com/eigengo/akka-patterns/wiki/Configuration very helpful. The basic idea is to implement a trait called Configured, which is populated by the main application. The actors can then use that trait to gain access to local, non-serializable objects such as MongoConnection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!