A Cluster Singleton in Akka is a feature that ensures a single instance of an actor is running across the entire cluster at any given time. This is useful for scenarios where you need centralized processing or coordination within a distributed system, but still want fault tolerance and failover support.
Single Instance Across the Cluster:
Automatic Failover:
Cluster Membership Awareness:
Location Transparency:
Singleton Manager:
Singleton Proxy:
Leader Node:
You need to define a SingletonManager and (optionally) a SingletonProxy in your code.
import akka.actor.{Actor, ActorSystem, Props}
import akka.cluster.singleton._
import com.typesafe.config.ConfigFactory
object ClusterSingletonExample extends App {
// Actor to be used as a singleton
class SingletonActor extends Actor {
override def receive: Receive = {
case message => println(s"Singleton Actor received: $message")
}
}
// Create ActorSystem with cluster configuration
val config = ConfigFactory.load("application.conf")
val system = ActorSystem("ClusterSystem", config)
// SingletonManager definition
val singletonManager = system.actorOf(
ClusterSingletonManager.props(
singletonProps = Props[SingletonActor], // Props for the singleton actor
terminationMessage = PoisonPill, // Message to terminate the singleton
settings = ClusterSingletonManagerSettings(system)
),
name = "singletonManager"
)
// SingletonProxy definition
val singletonProxy = system.actorOf(
ClusterSingletonProxy.props(
singletonManagerPath = "/user/singletonManager", // Path to SingletonManager
settings = ClusterSingletonProxySettings(system)
),
name = "singletonProxy"
)
// Send a message to the singleton actor via the proxy
singletonProxy ! "Hello, Singleton!"
}