• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala SnapshotOffer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了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) 
开发者ID:bassmake,项目名称:hi-akka-persistence,代码行数:62,代码来源:CustomerAccountActor.scala


示例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}")
  }

} 
开发者ID:acflorea,项目名称:catscaffe,代码行数:30,代码来源:CatsView.scala


示例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")
  }
} 
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:34,代码来源:FriendActor.scala


示例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}]")
} 
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:26,代码来源:SamplePersistenceActor.scala


示例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)
  }
} 
开发者ID:michelnossin,项目名称:ndb,代码行数:26,代码来源:PersistenceActor.scala


示例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"
} 
开发者ID:reinaudvr,项目名称:Organizer,代码行数:58,代码来源:UserPersistentActor.scala


示例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)
} 
开发者ID:marcuslange,项目名称:pileworx-domain-akka,代码行数:41,代码来源:AggregateRoot.scala


示例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() 
开发者ID:shigemk2,项目名称:my-event-sourced-sample,代码行数:54,代码来源:EventSourced.scala


示例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))
} 
开发者ID:alexgenon,项目名称:rtbffeedparser,代码行数:60,代码来源:SongRepositoryActor.scala



注:本文中的akka.persistence.SnapshotOffer类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Element类代码示例发布时间:2022-05-23
下一篇:
Scala Matcher类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap