本文整理汇总了Scala中akka.persistence.SnapshotOffer类的典型用法代码示例。如果您正苦于以下问题:Scala SnapshotOffer类的具体用法?Scala SnapshotOffer怎么用?Scala SnapshotOffer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SnapshotOffer类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CustomerAccountActor
//设置package包名称以及导入依赖的类
package sk.bsmk.akka.actors.customers
import akka.actor.{ActorLogging, Props}
import akka.persistence.{PersistentActor, SnapshotOffer}
class CustomerAccountActor(val persistenceId: String) extends PersistentActor with ActorLogging {
var state: CustomerAccount = CustomerAccount.initial
override def receiveRecover: Receive = {
case [email protected](actualPointBalance) =>
log.debug("recovering with event: {}", event)
state = state.copy(pointBalance = actualPointBalance)
case [email protected](_, snapshot: CustomerAccount) =>
log.debug("recovering with snapshot: {}", offer)
state = snapshot
}
override def receiveCommand: Receive = {
case AddPointsCommand(pointsToAdd) =>
persist(PointsChangedEvent(state.pointBalance + pointsToAdd)) { event =>
state = state.withPoints(event.actualPointBalance)
}
case ResetPointsCommand =>
persist(PointsChangedEvent(0)) { _ =>
state = state.resetPoints
}
case ChangeTierCommand(newTier) =>
persist(TierChangedEvent(newTier)) { event =>
state = state.withTier(event.actualTier)
}
case "snapshot" =>
log.debug("saving snapshot")
saveSnapshot(state)
case "print" =>
println(state)
}
}
object CustomerAccountActor {
def props(persistenceId: String): Props = Props(new CustomerAccountActor(persistenceId))
}
sealed trait CustomerAccountActorCommand
case class CreateAccountCommand(name: String)
case class AddPointsCommand(points: Int)
case object ResetPointsCommand
case class ChangeTierCommand(newTier: Tier)
case class PointsChangedEvent(actualPointBalance: Int)
case class TierChangedEvent(actualTier: Tier)
示例2: CatsView
//设置package包名称以及导入依赖的类
package catscaffe.views
import akka.actor.ActorLogging
import akka.persistence.{PersistentView, SaveSnapshotFailure, SaveSnapshotSuccess, SnapshotOffer}
class CatsView extends PersistentView with ActorLogging {
private var numReplicated = 0
override def persistenceId: String = "Fely"
override def viewId = "fely's-view"
def receive = {
case SnapshotOffer(metadata, snapshot: Int) =>
numReplicated = snapshot
log.debug(s"view received snapshot offer ${snapshot} (metadata = ${metadata})")
case payload if isPersistent =>
numReplicated += 1
log.debug(s"view replayed event ${payload} (num replicated = ${numReplicated})")
case SaveSnapshotSuccess(metadata) =>
log.debug(s"view saved snapshot (metadata = ${metadata})")
case SaveSnapshotFailure(metadata, reason) =>
log.debug(s"view snapshot failure (metadata = ${metadata}), caused by ${reason}")
case payload =>
log.debug(s"view received other message ${payload}")
}
}
示例3: FriendActor
//设置package包名称以及导入依赖的类
package com.packt.chapter6
import akka.actor.{ActorLogging, Props}
import akka.persistence.{PersistentActor, Recovery, RecoveryCompleted, SnapshotOffer}
object FriendActor {
def props(friendId: String, recoveryStrategy: Recovery) = Props(new FriendActor(friendId, recoveryStrategy))
}
class FriendActor(friendId: String, r: Recovery) extends PersistentActor with ActorLogging {
override val persistenceId = friendId
override val recovery = r
var state = FriendState()
def updateState(event: FriendEvent) = state = state.update(event)
val receiveRecover: Receive = {
case evt: FriendEvent =>
log.info(s"Replaying event: $evt")
updateState(evt)
case SnapshotOffer(_, recoveredState : FriendState) =>
log.info(s"Snapshot offered: $recoveredState")
state = recoveredState
case RecoveryCompleted => log.info(s"Recovery completed. Current state: $state")
}
val receiveCommand: Receive = {
case AddFriend(friend) => persist(FriendAdded(friend))(updateState)
case RemoveFriend(friend) => persist(FriendRemoved(friend))(updateState)
case "snap" => saveSnapshot(state)
case "print" => log.info(s"Current state: $state")
}
}
示例4: SamplePersistenceActor
//设置package包名称以及导入依赖的类
package com.packt.chapter6
import akka.persistence.{PersistentActor, SnapshotOffer}
class SamplePersistenceActor extends PersistentActor {
override val persistenceId = "unique-id-1"
var state = ActiveUsers()
def updateState(event: Event) = state = state.update(event)
val receiveRecover: Receive = {
case evt: Event => updateState(evt)
case SnapshotOffer(_, snapshot: ActiveUsers) => state = snapshot
}
val receiveCommand: Receive = {
case UserUpdate(userId, Add) => persist(AddUserEvent(userId))(updateState)
case UserUpdate(userId, Remove) => persist(RemoveUserEvent(userId))(updateState)
case "snap" => saveSnapshot(state)
case "print" => println(state)
case ShutdownPersistentActor => context.stop(self)
}
override def postStop() = println(s"Stopping [${self.path}]")
}
示例5: PersistenceActor
//设置package包名称以及导入依赖的类
package com.nossin.ndb
import akka.persistence.{PersistentActor, SnapshotOffer}
class PersistenceActor extends PersistentActor {
override val persistenceId = "unique-id-1"
var state = ActiveUsers()
def updateState(event: Event) = state = state.update(event)
val receiveRecover: Receive = {
case evt: Event => updateState(evt)
case SnapshotOffer(_, snapshot: ActiveUsers) => state =
snapshot
}
val receiveCommand: Receive = {
case UserUpdate(userId, Add) =>
persist(AddUserEvent(userId))(updateState)
case UserUpdate(userId, Remove) =>
persist(RemoveUserEvent(userId))(updateState)
case "snap" => saveSnapshot(state)
case "print" => println(state)
}
}
示例6: UserPersistentActor
//设置package包名称以及导入依赖的类
package persistence
import actors.UserActor.{AddUser, DeleteUserByFirstName, PrintCurrentUsers, SaveCurrentUsers}
import akka.persistence.{PersistentActor, SaveSnapshotFailure, SaveSnapshotSuccess, SnapshotOffer}
import events.{UserAdded, UserDeletedByFirstName}
import states.UsersState
class UserPersistentActor extends PersistentActor {
var state = UsersState()
def updateState(event: UserAdded): Unit =
state = state.userAdded(event)
def updateState(event: UserDeletedByFirstName): Unit =
state = state.userDeleted(event)
def numEvents =
state.size
val receiveRecover: Receive = {
case evt: UserAdded => updateState(evt)
case SnapshotOffer(_, snapshot: UsersState) => {
println(s"offered state = $snapshot")
state = snapshot
}
}
val receiveCommand: Receive = {
case AddUser(firstName, lastName) =>
persist(UserAdded(firstName, lastName)) { event =>
updateState(event)
context.system.eventStream.publish(event)
}
sender() ! "Hello, " + firstName + ". You are added to the system"
case DeleteUserByFirstName(firstName) =>
persist(UserDeletedByFirstName(firstName)) { event =>
updateState(event)
context.system.eventStream.publish(event)
}
sender() ! "Hello, " + firstName + ". You are deleted from the system"
case SaveCurrentUsers() => {
saveSnapshot(state)
sender() ! "1,2,3... Snapshot"
}
case SaveSnapshotSuccess(metadata) =>
println(s"SaveSnapshotSuccess(metadata) : metadata=$metadata")
case SaveSnapshotFailure(metadata, reason) =>
println("""SaveSnapshotFailure(metadata, reason) :
metadata=$metadata, reason=$reason""")
case PrintCurrentUsers() => {
println(state)
sender() ! "Check the logs for the print"
}
}
override def persistenceId = "user-persistent-actor"
}
示例7: persistenceId
//设置package包名称以及导入依赖的类
package io.pileworx.common.domain
import akka.actor.ActorLogging
import akka.persistence.{PersistentActor, SnapshotMetadata, SnapshotOffer}
trait AggregateRoot extends PersistentActor with ActorLogging {
override def persistenceId:String
protected var state:State = _
protected def updateState(evt: Event): Unit
protected def afterEventPersisted(evt: Event): Unit = {
updateAndRespond(evt)
publish(evt)
}
private def updateAndRespond(evt: Event): Unit = {
updateState(evt)
respond(evt)
}
protected def respond(response: AnyRef): Unit = {
sender() ! response
context.parent ! Acknowledge(persistenceId)
}
private def publish(event: Event) = context.system.eventStream.publish(event)
override val receiveRecover: Receive = {
case evt: Event =>
updateState(evt)
case SnapshotOffer(metadata, state: State) =>
restoreFromSnapshot(metadata, state)
log.debug("Recovering Aggregate from snapshot.")
}
protected def restoreFromSnapshot(metadata: SnapshotMetadata, state: State)
}
示例8: EventSourcedDriver
//设置package包名称以及导入依赖的类
package com.transactionalactor
import akka.actor.Actor.Receive
import akka.actor._
import akka.persistence.{EventsourcedProcessor, SnapshotOffer}
object EventSourcedDriver extends CompletableApp(4) {
}
trait DomainEvent
case class StartOrder(orderId: String, customerInfo: String)
case class OrderStarted(orderId: String, customerInfo: String) extends DomainEvent
case class AddOrderLineItem(productId: String, units: Int, price: Double)
case class OrderLineItemAdded(productId: String, units: Int, price: Double) extends DomainEvent
case class PlaceOrder()
case class OrderPlaced() extends DomainEvent
class Order extends EventsourcedProcessor {
var state: OrderState = _ // new OrderState()
def updateState(event: DomainEvent): Unit =
state = state.update(event)
val receiveRecover: Receive = {
case event: DomainEvent =>
updateState(event)
case SnapshotOffer(_, snapshot: OrderState) =>
state = snapshot
}
val receiveCommand: Receive = {
case startOrder: StartOrder =>
persist(OrderStarted(startOrder.orderId, startOrder.customerInfo)) (updateState)
case addOrderLineItem @ AddOrderLineItem =>
//persist(OrderStarted(addOrderLineItem., startOrder.customerInfo)) (updateState)
case placeOrder @ PlaceOrder =>
}
}
case class OrderState(
customerInfo: String,
lineItems: List[OrderLineItem],
placed: Boolean) {
def update(event: DomainEvent): OrderState = {
null
}
}
case class OrderLineItem()
示例9: SongRepositoryActor
//设置package包名称以及导入依赖的类
package actors
import java.time.LocalDateTime
import actors.SongRepositoryActor._
import akka.actor.{ActorLogging, Props}
import akka.persistence.{PersistentActor, SaveSnapshotFailure, SaveSnapshotSuccess, SnapshotOffer}
import domain.Song
class SongRepositoryActor (stationId: Int) extends PersistentActor with ActorLogging{
val broadCastActor = context.actorSelection("/user/broadCastActor")
override def persistenceId: String = "songRepository_"+stationId
var playedSongs = scala.collection.mutable.Map[LocalDateTime,Song]()
def skimFeed(songs: List[Song]):List[Song] = songs.filterNot{ s=> playedSongs.get(s.start).isDefined }
def addSong(ns:NewSong):Unit = { playedSongs += (ns.song.id -> ns.song)}
def commitSong(ns:NewSong):Unit = {
addSong(ns)
log.debug("New song: {}",ns.song)
broadCastActor ! ns
}
override def receiveCommand: Receive = {
case NewFeed(feed:List[Song]) => {
log.debug("Received feed {}",feed)
skimFeed(feed).foreach (song => { persist(NewSong(song)) (commitSong) })
saveSnapshot(playedSongs)
}
case GetFullList => sender ! FullList(playedSongs.values.toList)
case SaveSnapshotSuccess(metadata) => log.debug("Successfully save a snapshot {}",metadata)
case SaveSnapshotFailure(metadata,reason)=>log.error("could not save snapshot {}, because of {}",metadata,reason)
case ResetRepository => {
persist(ResetRepository) (_ => playedSongs.clear)
}
}
override def receiveRecover: Receive = {
case ns:NewSong => {
log.debug("Recovery for {}",ns.song)
addSong(ns)
}
case SnapshotOffer(metadata, offeredSnapshot) => {
playedSongs = offeredSnapshot.asInstanceOf[scala.collection.mutable.Map[LocalDateTime,Song]]
log.debug("(SnapshotOffer) - Recovered {}", playedSongs)
}
}
}
object SongRepositoryActor {
case class NewFeed(songs: List[Song])
case object GetFullList
case object ResetRepository
case class FullList(songs:List[Song])
case class NewSong(song:Song)
def props(stationId:Int):Props = Props(new SongRepositoryActor(stationId))
}