gpt4 book ai didi

scala - 如何获取 Akka 中现有 ActorSystem 的引用?

转载 作者:行者123 更新时间:2023-12-03 01:38:52 25 4
gpt4 key购买 nike

在 Akka (scala) 中是否可以获取对现有 ActorSystem 的引用?

我正在与 DB 的另一个 Actor 一起开发 Spray 应用程序。我还扩展了指令以让每个路径都有一个对象。这些指令本身并不是参与者,但它们需要将消息传递给 DBActor。这里:

class HttpActor extends Actor with HttpService {

val actorRefFactory = context

def receive = runRoute(
IndexService.route ~
HostsService.route
)
}

object HostsService extends Directives{
def route(implicit dm: DetachMagnet2) = {
path("hosts") {
get {
detach() {
**dbActor ! CreateHost**
complete("get me hosts!")
}
} ~
post {
detach() {
entity(as[String]) { payload =>
complete(s"post hosts $payload")
}
}
}
}
}
}

有没有办法让 HostsService 发现 ActorSystem 本身,以便他可以找到 DBActor,还是必须 HttpActor 将其传入?后者似乎不太优雅,因为 HostsService 需要成为一个类(而不是一个对象),因此不再是单例。

最佳答案

来自here :

there was a ticket for creating such a registry, but we were not satisfied with what we got when trying to specify the semantics in detail. One part is that we removed all global state so that different parts of an application can use Akka without having to worry about each other and a global feature would break this. Another is that it would encourage get-or-create usage—my pet peeve—which would make the semantics unclear: you give a name and a config, but if the name already exists you potentially get back a differently configured system (which is usually quite fatal).

There is nothing stopping you from putting a hashmap in some central place of your application, (pre-)populate that with the actor systems you need and be done, that's basically a one-liner (which is another reason for not including it in Akka, because instead of a simple solution to a very narrow problem we'd have to think of a solution to a much more generic problem)

就您而言,最好将系统隐式传递给 route 函数:

class HttpActor extends Actor with HttpService {

implicit val actorRefFactory = context

def receive = runRoute(
IndexService.route ~
HostsService.route
)
}

object HostsService extends Directives {
def route(implicit dm: DetachMagnet2, as: ActorContext) = {...}
}

关于scala - 如何获取 Akka 中现有 ActorSystem 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28399978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com