我正在处理使用Akka的应用程序。我有一个场景,参与者将以数组或列表的形式从数据库中获取特定值。子参与者将引用此列表,但不允许他们修改或更新此列表。
有没有办法在参与者之间共享数据?
发布于 2018-08-25 01:12:41
只需将父参与者从数据库填充的列表设置为不可变。然后,父母可以与孩子角色共享这个列表,而不用担心shared mutable state带来的陷阱。子角色可以向父角色请求列表,而父角色可以通过消息传递将列表发送给子角色。演员可能看起来像这样:
case object GetFromDb
case object GetList
case object ProcessList
class ParentActor extends Actor {
var fromDb: List[Something] = List()
def receive = {
case GetFromDb =>
// query the database and replace fromDb with a new list
fromDb = // ...
case GetList =>
sender() ! fromDb
}
}
class ChildActor(parent: ActorRef) extends Actor {
def receive = {
case ProcessList =>
// get the list from the parent
parent ! GetList
case fromDb: List[Something] =>
// do something with the list
}
}在上面的示例中,参与者按原样传递了一个不可变的列表,但是如果您愿意的话,可以很容易地将该列表放在case类中。还要注意,子参与者将对父参与者的引用作为构造函数参数,但是子参与者也可以使用context.parent来获取对其父参与者的引用。
https://stackoverflow.com/questions/52006036
复制相似问题