按需演员获取或创建

编程入门 行业动态 更新时间:2024-10-28 17:26:54
本文介绍了按需演员获取或创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以用 actorOf 创建演员,并用 actorFor 查看他们.我现在想通过一些 id:String 获取一个演员,如果它不存在,我希望它被创建.像这样:

I can create actors with actorOf and look them with actorFor. I now want to get an actor by some id:String and if it doesnt exist, I want it to be created. Something like this:

def getRCActor(id: String):ActorRef = { Logger.info("getting actor %s".format(id)) var a = system.actorFor(id) if(a.isTerminated){ Logger.info("actor is terminated, creating new one") return system.actorOf(Props[RC], id:String) }else{ return a } }

但这不起作用,因为 isTerminated 总是正确的,我得到 actor name 1 is not unique! 第二次调用的异常.我想我在这里使用了错误的模式.有人可以帮助如何实现这一目标吗?我需要

But this doesn't work as isTerminated is always true and I get actor name 1 is not unique! exception for the second call. I guess I am using the wrong pattern here. Can someone help how to achieve this? I need

  • 按需创建演员
  • 按 id 查找演员,如果不存在则创建他们
  • 继续破坏的能力,因为我不知道我是否会再次需要它

我应该为此使用调度程序还是路由器?

Should I use a Dispatcher or Router for this?

解决方案按照建议,我使用一个具体的主管,将可用的演员保存在地图中.可以要求提供他的一个孩子.

Solution As proposed I use a concrete Supervisor that holds the available actors in a map. It can be asked to provide one of his children.

class RCSupervisor extends Actor { implicit val timeout = Timeout(1 second) var as = Map.empty[String, ActorRef] def getRCActor(id: String) = as get id getOrElse { val c = context actorOf Props[RC] as += id -> c context watch c Logger.info("created actor") c } def receive = { case Find(id) => { sender ! getRCActor(id) } case Terminated(ref) => { Logger.info("actor terminated") as = as filterNot { case (_, v) => v == ref } } } }

他的伴生对象

object RCSupervisor { // this is specific to Playframework (Play's default actor system) var supervisor = Akka.system.actorOf(Props[RCSupervisor]) implicit val timeout = Timeout(1 second) def findA(id: String): ActorRef = { val f = (supervisor ? Find(id)) Await.result(f, timeout.duration).asInstanceOf[ActorRef] } ... }

推荐答案

我使用 akka 的时间并不长,但演员的创建者默认是他们的主管.因此,父母可以监听他们的终止;

I've not been using akka for that long, but the creator of the actors is by default their supervisor. Hence the parent can listen for their termination;

var as = Map.empty[String, ActorRef] def getRCActor(id: String) = as get id getOrElse { val c = context actorOf Props[RC] as += id -> c context watch c c }

但显然你需要注意他们的终止;

But obviously you need to watch for their Termination;

def receive = { case Terminated(ref) => as = as filterNot { case (_, v) => v == ref }

这是一个解决方案吗?我必须说我没有完全理解你的意思 终止总是正确的 => 演员姓名 1 不是唯一的!"

Is that a solution? I must say I didn't completely understand what you meant by "terminated is always true => actor name 1 is not unique!"

更多推荐

按需演员获取或创建

本文发布于:2023-11-25 03:46:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628188.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按需   演员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!