如何在 akka actorsystem

时间:2021-04-28 17:11:45

标签: scala akka akka-actor

我正在尝试在 Akka 中创建两个简单的 actor,一个创建一个世界(城市案例类列表)并将消息返回给 init actor。我在 Main.scala

有我的引导程序
object ActorInit {
  sealed trait Command
  case object Init extends Command

  def apply(): Behavior[Command] = Behaviors.setup(context => new ActorInit(context))
}

class ActorInit(context: ActorContext[ActorInit.Command])
extends AbstractBehavior[ActorInit.Command](context) {
  import ActorInit._
  override def onMessage(msg: Command): Behavior[Command] = msg match {
      case Init => {
        val world = context.spawn(World(),"world")
        world ! World.Create(200,200,5,this)  // what do I wrap "this" in?
        this
      }
  }
}

还有一个在World.scala中创建我的世界的课程

object World {
  sealed trait Command
  case class Create(width: Int, height: Int, count: Int, replyTo: ActorRef[ActorInit]) extends Command
  case class WorldMap(cities: List[City]) extends Command

  def apply(): Behavior[Command] = Behaviors.setup(new World(_))

  case class City(x: Int, y: Int)
}

class World(context: ActorContext[World.Command])
extends AbstractBehavior[World.Command](context) {
  import World._

  override def onMessage(msg: Command): Behavior[Command] = msg match {
    case Create(width, height, count, replyTo) => {
      replyTo ! WorldMap(generateCityList(width, height, count))
      this
    }
  }

  private def generateCityList(width: Int, height: Int, count: Int): List[City] = {
    // Create city list
  }
}

然后,我将在 onMessage 类的 ActorInit 方法中添加另一个案例,以侦听来自 WroldMap 演员的 World 消息。但是,当我运行它时,我收到以下错误:

[error] /home/matt/documents/small_projects/akka_TSP/src/main/scala/Main.scala:27:4
0: type mismatch;
[error]  found   : small.tsp.ActorInit
[error]  required: akka.actor.typed.ActorRef[small.tsp.ActorInit]
[error]         world ! World.Create(200,200,5,this)
[error]                                        ^

我知道我需要对签名 T => akka.actor.typed.ActorRef[T] 做一些事情,但是我查看了文档却找不到所需的命令。我错过了什么?

1 个答案:

答案 0 :(得分:1)

我在查看更多文档后找到了答案。我应该一直使用 context.self。所以我的 Init 案例看起来像:

      case Init => {
        val world = context.spawn(World(),"world")
        world ! World.Create(200,200,5,context.self)
        this
      }

并且我需要稍微更改 Create 案例类:

  case class Create(width: Int, height: Int, count: Int, replyTo: ActorRef[ActorInit.Command]) extends Command
相关问题