Akka远程角色,没有默认构造函数的超类 [英] Akka remote actors, superclass without default constructor

查看:105
本文介绍了Akka远程角色,没有默认构造函数的超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用akka远程角色发送消息,其中case类是其构造函数中采用参数的超类的子类。

I am trying to send a message using akka remote actors, where the case class is a subclass of a superclass taking argument in its constructor.

这里是最小值重现该问题的示例:

Here is a minimum example to reproduce the problem:

package com.tuvistavie.testremote

import akka.actor.{ Actor, ActorSystem, Props, ActorLogging }
import com.typesafe.config.ConfigFactory

abstract class Foo(val a: Int)
case class MessageFoo(override val a: Int) extends Foo(a)

object Sender {
  def main(args: Array[String]) {
    val system = ActorSystem("Sender", ConfigFactory.load.getConfig("sender"))
    val actor = system.actorFor("akka://Receiver@127.0.0.1:2552/user/receiver")
    actor ! MessageFoo(1)
  }
}

object Receiver {
  class ReceiverActor extends Actor with ActorLogging {
    def receive = {
      case m: MessageFoo => log.debug(m.toString)
    }
  }

  def main(args: Array[String]) {
    val system = ActorSystem("Receiver", ConfigFactory.load.getConfig("receiver"))
    val actor = system.actorOf(Props[ReceiverActor], "receiver")
  }
}

运行此代码时,出现以下错误:

When running this code, I get the following error:

[ERROR] [06/26/2013 02:53:16.132] [Receiver-9] 
[NettyRemoteTransport(akka://Receiver@127.0.0.1:2552)] 
RemoteServerError@akka://Receiver@127.0.0.1:2552] Error[java.io.InvalidClassException: com.tuvistavie.testremote.MessageFoo; no valid constructor]

我认为这是因为消息无法反序列化(使用 akka.serialization.JavaSerializer ),因为父母的构造函数。
如果只是一条或两条消息,我知道我可以编写自己的序列化程序,但是我的应用程序中有很多类似的case类。

I think it is because the message cannot be deserialized (using akka.serialization.JavaSerializer), because of the parents' constructor. If it were only one or two messages I know I could write my own serializer, but I have plenty of case classes like this in my application.

应该

推荐答案

如果您像这样进行重构,事情就可以了:

Things will work if you restructure like so:

trait Foo{
  val a:Int
}
case class MessageFoo(a:Int) extends Foo

我通常会尝试避免使用case类进行类继承。如果需要将一组案例类作为抽象类型进行引用,则可以使用特征。

I generally try and stay away from class inheritance with case classes. If I need to be able to refer to a set of case classes as an abstract type, I use traits instead.

这篇关于Akka远程角色,没有默认构造函数的超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆