gpt4 book ai didi

scala - Play Scala Akka WebSockets 更改 Actor 路径

转载 作者:行者123 更新时间:2023-12-01 09:51:16 24 4
gpt4 key购买 nike

我遵循了使用 Scala Play 和 Akka Actor 创建 Web 套接字的示例:

https://www.playframework.com/documentation/2.5.x/ScalaWebSockets#Handling-WebSockets-with-Akka-Streams-and-actors

在恢复时, Controller :

import play.api.mvc._
import play.api.libs.streams._

class Controller1 @Inject() (implicit system: ActorSystem, materializer: Materializer) {

def socket = WebSocket.accept[String, String] { request =>
ActorFlow.actorRef(out => MyWebSocketActor.props(out))
}

还有 Actor :
import akka.actor._

object MyWebSocketActor {
def props(out: ActorRef) = Props(new MyWebSocketActor(out))
}

class MyWebSocketActor(out: ActorRef) extends Actor {
def receive = {
case msg: String =>
out ! ("I received your message: " + msg)
}
}

创建的 Actor (每个 websocket 连接一个)是/user Actor 的 child 。我创建了 3 个连接,创建的 Actor 是:
  • /user/$b
  • /user/$c
  • /user/$d

  • 我想根据网络套接字消息的字段更改 Actor 的姓名。我怎么能这样做?

    最佳答案

    您可以按如下方式设置actor的名称:

  • 创建文件 BetterActorFlow.scala
    package your.package

    import akka.actor._
    import akka.stream.scaladsl.{Keep, Sink, Source, Flow}
    import akka.stream.{Materializer, OverflowStrategy}

    object BetterActorFlow {

    def actorRef[In, Out](props: ActorRef => Props, bufferSize: Int = 16, overflowStrategy: OverflowStrategy = OverflowStrategy.dropNew, maybeName: Option[String] = None)(implicit factory: ActorRefFactory, mat: Materializer): Flow[In, Out, _] = {

    val (outActor, publisher) = Source.actorRef[Out](bufferSize, overflowStrategy)
    .toMat(Sink.asPublisher(false))(Keep.both).run()

    def flowActorProps: Props = {
    Props(new Actor {
    val flowActor = context.watch(context.actorOf(props(outActor), "flowActor"))

    def receive = {
    case Status.Success(_) | Status.Failure(_) => flowActor ! PoisonPill
    case Terminated(_) => context.stop(self)
    case other => flowActor ! other
    }

    override def supervisorStrategy = OneForOneStrategy() { case _ => SupervisorStrategy.Stop }
    })
    }

    def actorRefForSink =
    maybeName.fold(factory.actorOf(flowActorProps)) { name => factory.actorOf(flowActorProps, name) }

    Flow.fromSinkAndSource(Sink.actorRef(actorRefForSink, Status.Success(())), Source.fromPublisher(publisher))

    }
    }
  • 使用 BetterActorFlow 代替 ActorFlow:
    BetterActorFlow.actorRef(out =>
    ChatActor.props(out), 16, OverflowStrategy.dropNew, Some("alicebob"))

  • 这对我有用。创建的 Actor 在 user/alicebob (将此与 context.system.actorSelection("user/alicebob") 一起使用)

    关于scala - Play Scala Akka WebSockets 更改 Actor 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37281559/

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