Search code examples
scalaakkaakka-remote-actor

Is there a way to send messages typed with my own classes to an Akka remote actor?


Is there a way to send messages typed with my own classes to a remote actor?
For instance I would like to be able to received in my remote actor a message like this:

case myClass: MyClass => doSomething()

But I get an error local class incompatible because the serialVersionUID are different.

The sole way to send a message of type MyClass that I have found is to serialize it in Json. But I have to serialize/deserialize it, and more problematic, I don't have a clean way to receive two kinds of typed messages...

So is there a way to send strongly typed messages to a remote actor? If not, what is the workaround?


Solution

  • You most certainly can!

    When sending objects over the network, they must be turned into bytes on one end, and turned back into objects on the other end. This is called 'Serialization'.

    In Akka the serialization mechanism used for messages travelling from one actor system to another is highly configurable: you shouldn't do it in your own actors, but leave it up to Akka's serialization infrastructure (and configure that to your liking).

    By default akka uses the built-in 'Java serialization'. This mostly works, but as you noticed is pretty picky about having the exact same class on both sides of the connection. Also, it is not particularly fast. You should have seen a warning in the logging:

    Using the default Java serializer for class [{}] which is not recommended because of performance implications. Use another serializer or disable this warning using the setting akka.actor.warn-about-java-serializer-usage

    To fix your problem you can either:

    • Keep using Java serialization, and at least fixate the serialVersionUID as described in Vitaliy's answer.
    • Switch to another serialization mechanism such as Protobuf.

    If you don't care too much about performance and don't expect to do 'rolling upgrades' (where you might need to convert between different versions of the same message), Java serialization is certainly the easiest. It's important to be aware of its limitations, though.

    Further documentation on how to configure akka's serialization mechanisms can be found at http://doc.akka.io/docs/akka/current/scala/serialization.html#serialization-scala