How do I load balance incoming messages onto the nodes of the Akka cluster?

To connect to an Akka cluster and send messages, you need to follow these steps:

  1. Enable Akka Cluster in your configuration: You need to specify the actor provider as “cluster” in your application.conf file. Here is an example:
akka {
  actor {
    provider = "cluster"
  }
  remote {
    artery {
      enabled = on
      canonical {
        hostname = "localhost"
        port = 2551
      }
    }
  }
  cluster {
    seed-nodes = [
      "akka://cluster-system@localhost:2551"
    ]
  }
}

Source

  1. Create an ActorSystem: An ActorSystem is a heavyweight structure that will allocate 1…N Threads, so create one per logical application.
Config config = ConfigFactory.load("application.conf");
ActorSystem system = ActorSystem.create("cluster-system", config);

Source

This example is using the classic actor api. To use the typed ActorSystem api, please have a look here.

  1. Send Messages: You can send messages to actors in the cluster using the tell method. Here is an example of how to send a message:
ActorRef publisher = system.actorOf(Props.create(SenderActor.class), "publisher");
publisher.tell("hello from microservice A ", null);

Source

  1. Serialization: You have to enable serialization to send messages between ActorSystems (nodes) in the Cluster. Serialization with Jackson is a good choice in many cases, and the recommended option if you don’t have other preferences or constraints.
    Source

  2. Distributed Publish Subscribe in Cluster: If you want to send a message to an actor without knowing which node it is running on, or send messages to all actors in the cluster that have registered interest in a named topic, you can use the DistributedPubSubMediator.
    Source

Remember, Akka Cluster is not a service discovery solution. New nodes need to know the address of at least one existing member of the cluster to join. This can be done with configuration, or Akka Management’s Cluster Bootstrap.