2013-10-15 09:01:07 +02:00
|
|
|
package sample.persistence
|
|
|
|
|
|
|
|
|
|
//#eventsourced-example
|
|
|
|
|
import akka.actor._
|
|
|
|
|
import akka.persistence._
|
|
|
|
|
|
2014-03-07 13:20:01 +01:00
|
|
|
final case class Cmd(data: String)
|
|
|
|
|
final case class Evt(data: String)
|
2013-10-15 09:01:07 +02:00
|
|
|
|
2014-03-07 13:20:01 +01:00
|
|
|
final case class ExampleState(events: List[String] = Nil) {
|
2013-10-15 09:01:07 +02:00
|
|
|
def update(evt: Evt) = copy(evt.data :: events)
|
|
|
|
|
def size = events.length
|
|
|
|
|
override def toString: String = events.reverse.toString
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class ExampleProcessor extends EventsourcedProcessor {
|
|
|
|
|
var state = ExampleState()
|
|
|
|
|
|
|
|
|
|
def updateState(event: Evt): Unit =
|
|
|
|
|
state = state.update(event)
|
|
|
|
|
|
|
|
|
|
def numEvents =
|
|
|
|
|
state.size
|
|
|
|
|
|
2014-01-19 17:46:32 +01:00
|
|
|
val receiveRecover: Receive = {
|
2013-12-03 16:34:26 +01:00
|
|
|
case evt: Evt => updateState(evt)
|
|
|
|
|
case SnapshotOffer(_, snapshot: ExampleState) => state = snapshot
|
2013-10-15 09:01:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
val receiveCommand: Receive = {
|
2013-12-03 16:34:26 +01:00
|
|
|
case Cmd(data) =>
|
2013-10-15 09:01:07 +02:00
|
|
|
persist(Evt(s"${data}-${numEvents}"))(updateState)
|
2013-12-03 16:34:26 +01:00
|
|
|
persist(Evt(s"${data}-${numEvents + 1}")) { event =>
|
2013-10-15 09:01:07 +02:00
|
|
|
updateState(event)
|
|
|
|
|
context.system.eventStream.publish(event)
|
|
|
|
|
if (data == "foo") context.become(otherCommandHandler)
|
|
|
|
|
}
|
2013-12-03 16:34:26 +01:00
|
|
|
case "snap" => saveSnapshot(state)
|
|
|
|
|
case "print" => println(state)
|
2013-10-15 09:01:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
val otherCommandHandler: Receive = {
|
2013-12-03 16:34:26 +01:00
|
|
|
case Cmd("bar") =>
|
|
|
|
|
persist(Evt(s"bar-${numEvents}")) { event =>
|
2013-10-15 09:01:07 +02:00
|
|
|
updateState(event)
|
|
|
|
|
context.unbecome()
|
|
|
|
|
}
|
|
|
|
|
unstashAll()
|
2013-12-03 16:34:26 +01:00
|
|
|
case other => stash()
|
2013-10-15 09:01:07 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
//#eventsourced-example
|
|
|
|
|
|
|
|
|
|
object EventsourcedExample extends App {
|
|
|
|
|
|
|
|
|
|
val system = ActorSystem("example")
|
|
|
|
|
val processor = system.actorOf(Props[ExampleProcessor], "processor-4-scala")
|
|
|
|
|
|
|
|
|
|
processor ! Cmd("foo")
|
|
|
|
|
processor ! Cmd("baz") // will be stashed
|
|
|
|
|
processor ! Cmd("bar")
|
|
|
|
|
processor ! "snap"
|
|
|
|
|
processor ! Cmd("buzz")
|
|
|
|
|
processor ! "print"
|
|
|
|
|
|
|
|
|
|
Thread.sleep(1000)
|
|
|
|
|
system.shutdown()
|
|
|
|
|
}
|