Last active
March 27, 2019 16:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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