问题
I am trying to find the best approach to sharing the same pool of connection between actors withing the cluster workers. I have the following structure:
Master Actor -> Worker Actors(can be up to 100 or more) -> MongoDB
Between workers and MongoDB I want to put reactivemongo, however I am not sure how exactly to provide connection pool sharing between all actors.
According to reactivemongo documentation:
A MongoDriver instance manages an actor system; a connection manages a pool of connections. In general, MongoDriver or create a MongoConnection are never instantiated more than once. You can provide a list of one ore more servers; the driver will guess if it's a standalone server or a replica set configuration. Even with one replica node, the driver will probe for other nodes and add them automatically.
Should I just create it in Master actor and then bundle with each message? So, this would be in Master actor:
val driver = new MongoDriver
val connection = driver.connection(List("localhost"))
And then I pass connection to actors in a message. Or should I query a connection in each Work Actor and pass just driver in a message?
Any help is very appreciated. Thanks.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/18638570/akka-and-reactivemongo