加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何在Akka中获取对现有ActorSystem的引用?

发布时间:2020-12-16 19:13:19 所属栏目:安全 来源:网络整理
导读:是否可以在Akka( scala)中获取对现有ActorSystem的引用? 我正在与另一个DB的Actor一起开发Spray应用程序.我也在扩展Directives以获得每个路径的对象.指令本身不是actor,但是它们需要将消息传递给DBActor.这里: class HttpActor extends Actor with HttpSer
是否可以在Akka( scala)中获取对现有ActorSystem的引用?

我正在与另一个DB的Actor一起开发Spray应用程序.我也在扩展Directives以获得每个路径的对象.指令本身不是actor,但是它们需要将消息传递给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)

在您的情况下,最好将您的系统隐式传递给路由功能:

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) = {...}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读