我目前正在努力閱讀我的演員的狀態,所以在這種情況下,我只想從我的 State 類中獲取歷史引數 - 例如在呼叫端點時列印它。
我已經成功地做到了?之前的操作員,但我從未嘗試過事件溯源。
到目前為止,我的代碼是這樣的:
object MyPersistentBehavior {
sealed trait Command
final case class Add(data: String) extends Command
case object Clear extends Command
sealed trait Event
final case class Added(data: String) extends Event
case object Cleared extends Event
final case class State(history: List[String] = Nil)
val commandHandler: (State, Command) => Effect[Event, State] = { (state, command) =>
command match {
case Add(data) => Effect.persist(Added(data))
case Clear => Effect.persist(Cleared)
}
}
val eventHandler: (State, Event) => State = { (state, event) =>
event match {
case Added(data) => state.copy((data :: state.history).take(5))
case Cleared => State(Nil)
}
}
def apply(id: String): Behavior[Command] =
EventSourcedBehavior[Command, Event, State](
persistenceId = PersistenceId.ofUniqueId(id),
emptyState = State(Nil),
commandHandler = commandHandler,
eventHandler = eventHandler)
}
在我的主要方法中,我想列印狀態:
val personActor: ActorSystem[MyPersistentBehavior.Command] = ActorSystem(MyPersistentBehavior("IDDD"), "AHA")
//personActor ? GetState <- something like this
謝謝!!
uj5u.com熱心網友回復:
我沒有在akka中使用過事件采購,但是快速查看了檔案,我認為這可能會有所幫助:
case class GetState(replyTo: ActorRef[StatusReply[AddPostDone]]) extends Command
// and in the match for commands:
...
case GetState(replyTo) =>
replyTo ! StatusReply.Success(state)
// or if replyTo was of type ActorRef[State] =>
replyTo ! state
Effect在 akka 的事件溯源檔案中也有這個,看起來很有趣:
def onCommand(subscriber: ActorRef[State], state: State, command: Command): Effect[Event, State] = {
command match {
case Add(data) =>
Effect.persist(Added(data)).thenRun(newState => subscriber ! newState)
case Clear =>
Effect.persist(Cleared).thenRun((newState: State) => subscriber ! newState).thenStop()
}
}
如您所見,它非常易于使用。也可以在每次效果后回復最新狀態:
case class AddCommand(number: Int, replyTo: ActorRef[State]) extends Command
// in the command handler
case add: AddCommand(num, replyTo) =>
// your logic here
Event.persist(Added(num)) thenRun { newState =>
replyTo ! newState
}
檔案中還有很多其他選項,因此我強烈建議您查看:https ://doc.akka.io/docs/akka/current/typed/persistence.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/486232.html
