简体   繁体   English

演员消息应该在哪里宣布?

[英]Where should actor messages be declared?

I'm developing an application using Akka, and a thing that kind of bugs me the whole time regards message declaration with the Actor 's. 我正在使用Akka开发一个应用程序,这个问题让我一直认为我和Actor的消息声明一样。 Where should I declare the messages? 我应该在哪里声明消息? In the receivers companion object or the senders companion object or on some third place? 在接收器伴侣对象或发送者伴侣对象或第三位?

The Akka team recommends Message should be defined in the same place the props method should be: in the Receiver's Companion object because the Receiver implements the receive partial function and needs to know about all the messages it supports. Akka团队建议Message应该在props方法的相同位置定义: 在Receiver的Companion对象中,因为Receiver实现了receive部分功能,需要知道它支持的所有消息。 Also, multiple senders can send a set of messages (implemented by the Receiver), so you cannot put it in one single sender. 此外,多个发件人可以发送一组邮件(由Receiver实现),因此您无法将其放在一个发件人中。

If the official Typesafe Activator template activator-akka-scala-seed is of any importance regarding Akka's good practices the messages should be part of companion object as shown in the following PingActor actor (copied directly from the template): 如果正式的Typesafe Activator模板激活器-akka-scala-seed对于Akka的良好实践至关重要,则消息应该是伴随对象的一部分,如以下PingActor actor所示(直接从模板复制):

package com.example

import akka.actor.{Actor, ActorLogging, Props}

class PingActor extends Actor with ActorLogging {
  import PingActor._

  var counter = 0
  val pongActor = context.actorOf(PongActor.props, "pongActor")

  def receive = {
    case Initialize => 
      log.info("In PingActor - starting ping-pong")
      pongActor ! PingMessage("ping")   
    case PongActor.PongMessage(text) =>
      log.info("In PingActor - received message: {}", text)
      counter += 1
      if (counter == 3) context.system.shutdown()
      else sender() ! PingMessage("ping")
  } 
}

object PingActor {
  val props = Props[PingActor]
  case object Initialize
  case class PingMessage(text: String)
}

Note PingActor that holds all the accepted messages by the actor (as you may've noticed it's not followed strictly since PongActor.PongMessage is also accepted, but not defined in the companion object PingActor ). 注意PingActor包含PingActor所有接受的消息(因为您可能已经注意到它没有严格遵循,因为PongActor.PongMessage也被接受,但未在伴随对象PingActor定义)。

From another question How to restrict actor messages to specific types? 从另一个问题如何将演员消息限制为特定类型? the Viktor said : 尤说

The common practice is to declare what messages an Actor can receive in the companion object of the Actor, which makes it very much easier to know what it can receive. 通常的做法是声明Actor可以在Actor的伴随对象中接收哪些消息,这使得更容易知道它可以接收什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM