Arya
Arya

Reputation: 3039

Akka: Add custom serializer programmatically

Based on Akka serialization documents, we can implement our own serializer and register it by configuration. Is it possible to register our own serializer programmatically (not by configuration), for example by the ActorSystem instance?

UPDATE:

Something like this:

ActorSystem actorSystem = ActorSystem.create("app");
actorSystem.registerSerializer(MySerializable.class, MyOwnSerializer());

instead of:

actor {
  serializers {
    custom = "x.y.z.MyOwnSerializer"
  }
  serialization-bindings {
    "x.y.z.MySerializable" = custom
  }
}

Upvotes: 1

Views: 301

Answers (1)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22615

Serializers are created from config by querying akka.actor.serializers, so there is no direct option to override them using methods like registerSerializer.

What you can do instead, is programmatically create Config object and then pass it explicitly as the second parameter to ActorSystem.create. For example, you could do:

import com.typesafe.config._
//scala.collection.JavaConverters were deprecated in Scala 2.13
import scala.jdk.CollectionConverters._ 

val config = ConfigFactory.load() //load default values
     //override 'akka.actor.serializers'
     .withValue(
         "akka.actor.serializers", 
         ConfigValueFactory.fromMap(Map("hello" -> "x.y.z.MyOwnSerializer").asJava                   
     ).resolve()

val systemWithCustomConfig = ActorSystem.create("app", config)

Upvotes: 1

Related Questions