Skip to content

Instantly share code, notes, and snippets.

@jboner
Last active March 27, 2019 16:43
Show Gist options
  • Save jboner/9990435 to your computer and use it in GitHub Desktop.
Save jboner/9990435 to your computer and use it in GitHub Desktop.
A game of ping pong using two Akka Actors, persisted using Event Sourcing through Akka Persistence
package demo
import akka.actor.{Props, ActorSystem}
import akka.persistence.PersistentActor
object PingPong extends App {
case object Ball // The Command
case object BallReceived // The Domain Event, represents a Fact, something that have already happened
class Ping extends PersistentActor {
val persistenceId = "Ping"
var counter = 0 // Mutable state
def increment() = counter += 1 // State changing function
def receiveCommand = {
case Ball => // When we receive a Command:
increment() // 1. Perform the state changes
persist(BallReceived) { event => // 2. Generate the event, then try to persist it
println(s"Ping counter: ${counter}") // 3. If successful, then perform the side-effects
sender.tell(Ball, self)
Thread.sleep(1000) // You should *never* call Thread.sleep in a real application, just here to slow things down
}
}
def receiveRecover = {
case BallReceived => increment() // On replay (recover etc), only run the state changes
}
}
class Pong extends PersistentActor {
val persistenceId = "Pong"
var counter = 0
def increment() = counter += 1
def receiveCommand = {
case Ball =>
increment()
persist(BallReceived) { event =>
println(s"Pong counter: ${counter}")
sender.tell(Ball, self)
Thread.sleep(1000)
}
}
def receiveRecover = {
case BallReceived => increment()
}
}
val system = ActorSystem("pingpong")
val ping = system.actorOf(Props(classOf[Ping]), "ping")
val pong = system.actorOf(Props(classOf[Pong]), "pong")
ping.tell(Ball, pong)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment