本文整理汇总了Scala中akka.persistence.PersistentActor类的典型用法代码示例。如果您正苦于以下问题:Scala PersistentActor类的具体用法?Scala PersistentActor怎么用?Scala PersistentActor使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PersistentActor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Counter
//设置package包名称以及导入依赖的类
package reactive4.performance
import akka.persistence.{PersistentActor, RecoveryCompleted}
class Counter extends PersistentActor {
import Counter._
override def persistenceId: String = "test-persistent-actor-counter"
var state = CounterState(0)
val objectCreatedTime = System.nanoTime()
def updateState(event: IncrementedEvent) = this.state = CounterState(state.counter + 1)
override def receiveRecover: Receive = {
case event: IncrementedEvent => updateState(event)
case event: RecoveryCompleted => println(s"Recovery time in seconds: ${(System.nanoTime() - objectCreatedTime).toSeconds}")
}
override def receiveCommand: Receive = {
case IncrementCommand => persist(IncrementedEvent())(updateState)
case PrintCounter => {
println(s"Counter value: ${state.counter}")
println(s"Write time in seconds: ${(System.nanoTime() - objectCreatedTime).toSeconds}")
}
}
}
object Counter {
case object IncrementCommand
case object PrintCounter
case class IncrementedEvent()
case class CounterState(counter: Long)
implicit class Nanoseconds(nanoseconds: Long) {
def toSeconds = nanoseconds / 1000000000d
}
}
示例2: commandHandler
//设置package包名称以及导入依赖的类
package lib.tools
import akka.actor.ActorLogging
import akka.persistence.PersistentActor
import lib.models.PayLoad
import scala.concurrent.duration._
trait Monitor extends PersistentActor with ActorLogging {
context.setReceiveTimeout(120.seconds)
final val persistenceId: String = self.path.name
def commandHandler: Receive
def recoverHandler:Receive
final def receiveRecover: Receive = defaultRecoverHandler orElse recoverHandler
final def receiveCommand: Receive = defaultCommandHandler orElse commandHandler
final def defaultCommandHandler: Receive = {
case payLoad: PayLoad => log.warning(s"No command handler for Payload [$payLoad] for the monitor $persistenceId")
}
final def defaultRecoverHandler: Receive = {
case msg => log.warning(s"No recover handler for msg [$msg] for the monitor $persistenceId")
}
}
示例3: ChunkedHermesGameFileEntries
//设置package包名称以及导入依赖的类
package proton.game.hermes
import java.util.UUID
import akka.actor.ActorLogging
import akka.event.LoggingReceive
import akka.persistence.PersistentActor
import scala.collection.mutable.ListBuffer
object ChunkedHermesGameFileEntries {
trait EntriesMessage
case class AppendEntries(entries: Seq[HermesGameFileEntry]) extends EntriesMessage
case class GetEntries() extends EntriesMessage
trait EntriesEvent
case class EntriesAppended(entries: Seq[HermesGameFileEntry]) extends EntriesEvent
trait EntriesResult
case class EntriesAppendedResult(id: UUID, count: Int) extends EntriesResult
case class GetEntriesResult(id: UUID, entries: Seq[HermesGameFileEntry]) extends EntriesResult
val gameFileEntriesRegionName = "hermesGameFileEntries"
}
class ChunkedHermesGameFileEntries(moduleSettings: HermesGameTickerModuleSettings) extends PersistentActor with ActorLogging {
import context._
import ChunkedHermesGameFileEntries._
private val _id: UUID = UUID.fromString(self.path.name)
private val _entries = new ListBuffer[HermesGameFileEntry]()
setReceiveTimeout(moduleSettings.chunkedTimeout)
override def receiveRecover: Receive = {
case event: EntriesEvent => updateState(event)
}
def updateState(e: EntriesEvent) = e match {
case EntriesAppended(entries) => _entries ++= entries
}
override def receiveCommand: Receive = LoggingReceive {
case AppendEntries(entries) =>
if (entries.nonEmpty) {
persist(EntriesAppended(entries))(e => {
updateState(e)
sender ! EntriesAppendedResult(_id, entries.size)
})
} else {
sender ! EntriesAppendedResult(_id, 0)
}
case GetEntries() => sender ! GetEntriesResult(_id, _entries)
}
override def persistenceId: String = "hermes-game-file-entries-" + _id.toString
}
示例4: AuthActor
//设置package包名称以及导入依赖的类
package antikkor.example.auth
import akka.persistence.PersistentActor
import Model._
class AuthActor extends PersistentActor with AuthAdapterActor {
override val persistenceId: String = "AuthActor"
private var authenticator: Authenticator = Authenticator()
override def receiveCommand: Receive = {
case Authenticate(user: User) => authenticate(user)
case Verify(token) => verify(token)
case Invalidate(token) => invalidate(token)
}
private def authenticate(user: User): Unit =
if (authenticator.isValidUser(user)) {
persist(Authenticated(user, authenticator.nextToken)) { event =>
updateState(event)
sender() ! translate(event)
}
} else {
sender() ! translate(InvalidUser(user))
}
private def verify(token: Token): Unit =
authenticator.validateToken(token) match {
case None => sender() ! translate(InvalidToken(token))
case Some(user) => sender() ! translate(Verified(user, token))
}
private def invalidate(token: Token): Unit =
authenticator.validateToken(token) match {
case None => sender() ! translate(InvalidToken(token))
case Some(user) => persist(Invalidated(user, token)) { event =>
updateState(event)
sender() ! translate(event)
}
}
private def updateState(event: Event): Unit = event match {
case Authenticated(user, token) => authenticator = authenticator.signIn(user, token)
case Verified(user, token) => ()
case Invalidated(user, token) => authenticator = authenticator.signOut(token)
}
override def receiveRecover: Receive = {
case event: Event => updateState(event)
}
}
示例5: BlogActor
//设置package包名称以及导入依赖的类
package antikkor.example.blog
import akka.persistence.PersistentActor
import antikkor.example.blog.Model._
class BlogActor extends PersistentActor with BlogAdapterActor {
var posts: List[Post] = Nil
override def persistenceId: String = "BlogActor"
override def receiveCommand: Receive = {
case AllPosts => sender() ! translate(Posts(posts))
case Publish(post) => persist(Published(post)) { event =>
updateState(event)
sender() ! translate(event)
}
}
override def receiveRecover: Receive = {
case event: Published => updateState(event)
}
private def updateState(event: Published): Unit = posts ::= event.post
}
示例6: 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)
示例7: AbstractAccount
//设置package包名称以及导入依赖的类
package com.franklevering.banking.domain.model.account
import java.util.UUID
import akka.persistence.PersistentActor
import akka.persistence.journal.Tagged
import com.franklevering.common.domain.event.Event
import com.franklevering.ports.adapters.http.request.handlers.CreateCheckingsAccountResponse
abstract class AbstractAccount()
case class CheckingsAccountCreated(id: UUID, balance: BigDecimal = 0.0) extends Event
case class CreateCheckingsAccount(name: String)
case class CheckingsAccount(id: UUID, balance: BigDecimal = 0.0) extends AbstractAccount ()
case class SavingsAccountCreated(id: UUID, balance: BigDecimal = 0.0) extends Event
case class CreateSavingsAccount(id: UUID)
case class SavingsAccount(id: UUID, balance: BigDecimal = 0.0) extends AbstractAccount()
case class WithdrawMoney(id: UUID, amount: BigDecimal)
case class MoneyWithdrawn(id: UUID, amount: BigDecimal) extends Event
class Account(id: UUID) extends PersistentActor {
var state: Option[AbstractAccount] = None
var balance: BigDecimal = 0.0
override def receiveRecover: Receive = {
case checkingsAccountCreated: CheckingsAccountCreated => updateState(checkingsAccountCreated)
}
override def receiveCommand: Receive = {
case createCheckingsAccount: CreateCheckingsAccount =>
persist(Tagged(CheckingsAccountCreated(id), Set("account"))) { event =>
val checkingsAccountCreatedEvent = event.payload.asInstanceOf[CheckingsAccountCreated]
updateState(checkingsAccountCreatedEvent)
sender ! CreateCheckingsAccountResponse(checkingsAccountCreatedEvent.id.toString)
}
case withdrawMoney: WithdrawMoney =>
if ((balance - withdrawMoney.amount) < 0) {
throw new Exception("Not enough funds")
}
persist(Tagged(MoneyWithdrawn(withdrawMoney.id, withdrawMoney.amount), Set("withdrawn"))) { event =>
updateState(event.payload.asInstanceOf[MoneyWithdrawn])
}
}
def updateState(evt: Event): Unit = {
evt match {
case checkingsAccountCreated: CheckingsAccountCreated =>
state = Some(CheckingsAccount(checkingsAccountCreated.id, checkingsAccountCreated.balance))
balance = checkingsAccountCreated.balance
}
}
override def persistenceId: String = s"account-$id"
}
示例8: migrationName
//设置package包名称以及导入依赖的类
package im.actor.server.migrations
import java.time.Instant
import akka.actor.{ Actor, ActorLogging, ActorSystem }
import akka.http.scaladsl.util.FastFuture
import akka.persistence.PersistentActor
import akka.util.Timeout
import im.actor.config.ActorConfig
import im.actor.server.KeyValueMappings
import shardakka.{ InstantCodec, ShardakkaExtension }
import scala.concurrent.duration._
import scala.concurrent.{ Await, Future, Promise }
trait Migration {
protected def migrationName: String
protected def migrationTimeout: Duration
protected def startMigration()(implicit system: ActorSystem): Future[Unit]
def migrate()(implicit system: ActorSystem): Unit = {
import system.dispatcher
implicit val kvTimeout = Timeout(ActorConfig.defaultTimeout)
val migrations = ShardakkaExtension(system).simpleKeyValue[Instant](KeyValueMappings.Migrations, InstantCodec)
Await.result(migrations.get(migrationName) flatMap {
case Some(date) ?
system.log.debug(s"Migration $migrationName will not run. Already completed at $date")
FastFuture.successful(())
case _ ?
system.log.warning(s"Migration $migrationName started")
startMigration() flatMap { _ ?
system.log.info(s"Migration $migrationName finished")
migrations.upsert(migrationName, Instant.now())
}
} recover {
case e ?
system.log.error(e, s"Migration $migrationName failed!!!")
throw e
}, migrationTimeout)
}
}
abstract class Migrator(promise: Promise[Unit]) extends Actor with ActorLogging {
override def preRestart(reason: Throwable, message: Option[Any]): Unit = {
log.error(reason, "Migrator failure")
super.preRestart(reason, message)
promise.failure(reason)
}
}
abstract class PersistentMigrator(promise: Promise[Unit]) extends Migrator(promise) with PersistentActor {
override protected def onRecoveryFailure(cause: Throwable, event: Option[Any]): Unit = {
super.onRecoveryFailure(cause, event)
promise.failure(cause)
}
}
示例9: ShiteTalker
//设置package包名称以及导入依赖的类
package com.mooneyserver.dublinpubs.shite_talking.protocol.actors
import akka.actor.ActorLogging
import akka.persistence.{PersistentActor, RecoveryCompleted}
import com.mooneyserver.dublinpubs.shite_talking.protocol.actors.models.{DrunkenWaffleReceived, DrunkenWaffle, ShiteTalkerIsYapping}
class ShiteTalker extends PersistentActor with ActorLogging {
val persistenceId: String = self.path.name
override def receiveRecover: Receive = {
case a: Any => log.info(s"$persistenceId is recovering: with some message $a")
case RecoveryCompleted => log.info(s"$persistenceId has fully recovered")
}
override def receiveCommand: Receive = {
case ShiteTalkerIsYapping(_) => log.info(s"$persistenceId has been marked as Active")
case msg: DrunkenWaffle if msg.wafflerId == persistenceId =>
persistAsync(msg) {
waffle =>
log.info(s"$persistenceId has stored a message that it owns")
sender() ! DrunkenWaffleReceived(msg.waffleId)
}
case msg: DrunkenWaffle if msg.targetOfAbuseId == persistenceId =>
persistAsync(msg) {
waffle =>
log.info(s"$persistenceId has stored a message that it received")
// if client is active then send to Client
// else stash the messages in state
}
case a: Any => log.warning(s"Unexpected message received by Shite Talker: $a")
}
}
示例10: UserState
//设置package包名称以及导入依赖的类
package com.softwaremill.sandbox.application
import akka.actor.{ActorLogging, ActorRef, Status}
import akka.cluster.sharding.ShardRegion.HashCodeMessageExtractor
import akka.persistence.PersistentActor
import com.softwaremill.sandbox.application.UserActor.{CreateUser, UserCreated}
import [email protected]@
case class UserState(name: String)
class UserActor extends PersistentActor with ActorLogging {
var userState: Option[UserState] = None
override def receiveRecover: Receive = {
case event: UserCreated => userState = Some(UserState(event.name))
}
override def receiveCommand: Receive = {
case command: CreateUser =>
val currentSender = sender()
log.debug("creating used")
Thread.sleep(2500)
persist(UserCreated(command.name)) { e =>
userState = Some(UserState(e.name))
Thread.sleep(1500)
log.debug("user created")
currentSender ! Status.Success(e.name)
}
}
override def persistenceId: String = s"UA-${self.path.name}"
}
trait UserCommand {
def userId: String
}
object UserActor {
case class CreateUser(userId: String, name: String) extends UserCommand
case class UserCreated(name: String)
trait UserRegionTag
type UserRegion = ActorRef @@ UserRegionTag
}
class UserActorMessageExtractor extends HashCodeMessageExtractor(10) {
override def entityId(message: Any): String = message match {
case command: UserCommand => command.userId
}
}
示例11: HmdaPersistentActor
//设置package包名称以及导入依赖的类
package hmda.persistence.model
import java.util.concurrent.TimeUnit
import akka.actor.ReceiveTimeout
import akka.persistence.PersistentActor
import akka.stream.ActorMaterializer
import hmda.persistence.messages.CommonMessages.{ Event, Shutdown }
import hmda.persistence.PersistenceConfig._
import scala.concurrent.duration.Duration
abstract class HmdaPersistentActor extends PersistentActor with HmdaActor {
implicit val system = context.system
implicit val ec = system.dispatcher
implicit val materializer = ActorMaterializer()
def updateState(event: Event): Unit
override def preStart(): Unit = {
super.preStart()
val timeout = configuration.getInt("hmda.persistent-actor-timeout")
context.setReceiveTimeout(Duration.create(timeout, TimeUnit.SECONDS))
}
override def receiveCommand: Receive = {
case ReceiveTimeout =>
self ! Shutdown
case Shutdown =>
context stop self
}
override def receiveRecover: Receive = {
case event: Event => updateState(event)
}
}
示例12: UserManager
//设置package包名称以及导入依赖的类
package homeworkzen.domain.command.actor
import java.time.Instant
import java.util.UUID
import akka.actor.Props
import akka.persistence.PersistentActor
import homeworkzen.domain.command.message._
import homeworkzen.model._
import scala.collection.mutable
sealed class UserManager extends PersistentActor {
private val usernameToEntry: mutable.Map[String, UserEntry] = mutable.Map.empty
override def receiveRecover: Receive = {
case userCreated: UserCreatedEvent => apply(userCreated)
}
private def apply(userCreated: UserCreatedEvent): Unit = {
usernameToEntry += userCreated.userEntry.username -> userCreated.userEntry
}
override def receiveCommand: Receive = {
case createUser: CreateUserCommand => handle(createUser)
}
private def handle(createUser: CreateUserCommand): Unit = {
if (usernameToEntry.contains(createUser.username)) {
sender ! CreateUserResult(createUser, Left(UsernameAlreadyExist))
} else {
val userId = UserId(UUID.randomUUID())
val originalSender = sender
persist(UserCreatedEvent(Instant.now(), UserEntry(userId, createUser.username, createUser.hashedPassword))) { event =>
apply(event)
originalSender ! CreateUserResult(createUser, Right(userId))
}
}
}
override def persistenceId: String = self.path.parent.name + "-" + self.path.name
}
示例13: UnitWorker
//设置package包名称以及导入依赖的类
package homeworkzen.domain.command.actor
import java.time.Instant
import akka.persistence.PersistentActor
import homeworkzen.domain.command.message._
import homeworkzen.model._
sealed class UnitWorker(userId: UserId, unitId: UnitId, maximumCapacity: Long, unitType: UnitType) extends PersistentActor {
private var currentAmount: Long = 0
override def receiveRecover: Receive = {
case deposit: DepositEvent => apply(deposit)
case withdraw: WithdrawEvent => apply(withdraw)
}
private def apply(deposit: DepositEvent): Unit = currentAmount = currentAmount + deposit.amountDeposited
private def apply(withdraw: WithdrawEvent): Unit = currentAmount = currentAmount - withdraw.amountWithdrawn
override def receiveCommand: Receive = {
case deposit: DepositCommand => handle(deposit)
case withdraw: WithdrawCommand => handle(withdraw)
}
private def handle(deposit: DepositCommand): Unit = {
if (deposit.amountToDeposit <= 0) {
sender ! DepositResult(deposit, Left(InvalidDepositAmount))
} else if (currentAmount + deposit.amountToDeposit > maximumCapacity) {
sender ! DepositResult(deposit, Left(DepositExceedCapacity))
} else {
val originalSender = sender
persist(DepositEvent(Instant.now(), userId, unitId, deposit.amountToDeposit)) { event =>
apply(event)
originalSender ! DepositResult(deposit, Right(currentAmount))
}
}
}
private def handle(withdraw: WithdrawCommand): Unit = {
if (withdraw.amountToWithdraw <= 0) {
sender ! WithdrawResult(withdraw, Left(InvalidWithdrawAmount))
} else if (withdraw.amountToWithdraw > currentAmount) {
sender ! WithdrawResult(withdraw, Left(WithdrawExceedAvailableAmount))
} else {
val originalSender = sender
persist(WithdrawEvent(Instant.now(), userId, unitId, withdraw.amountToWithdraw)) { event =>
apply(event)
originalSender ! WithdrawResult(withdraw, Right(currentAmount))
}
}
}
override def persistenceId: String = s"unitworker-${unitId.id}"
}
示例14: UserWorker
//设置package包名称以及导入依赖的类
package homeworkzen.domain.command.actor
import java.time.Instant
import java.util.UUID
import akka.actor.Props
import akka.persistence.PersistentActor
import homeworkzen.domain.command.message._
import homeworkzen.model._
sealed class UserWorker extends PersistentActor {
override def receiveRecover: Receive = {
case unitCreated: UnitCreatedEvent => apply(unitCreated)
}
private def apply(unitCreated: UnitCreatedEvent): Unit = {
val props = Props(new UnitWorker(unitCreated.userId, unitCreated.unitId, unitCreated.maximumCapacity, unitCreated.unitType))
context.actorOf(props, unitCreated.unitId.id.toString)
}
override def receiveCommand: Receive = {
case createUnit: CreateUnitCommand => handle(createUnit)
case unitCommand: UnitCommand => forward(unitCommand)
}
private def handle(createUnit: CreateUnitCommand): Unit = {
if (createUnit.maximumCapacity <= 0) {
sender ! CreateUnitResult(createUnit, Left(InvalidMaximumCapacityValue))
} else {
val unitId = UnitId(UUID.randomUUID())
val originalSender = sender
persist(UnitCreatedEvent(Instant.now(), createUnit.userId, unitId, createUnit.maximumCapacity, createUnit.unitType)) { event =>
apply(event)
originalSender ! CreateUnitResult(createUnit, Right(unitId))
}
}
}
private def forward(unitCommand: UnitCommand): Unit = {
context.child(unitCommand.unitId.id.toString) match {
case Some(child) => child forward unitCommand
case None => sender ! unitCommand.unitForwardFailureMessage
}
}
override def persistenceId: String = self.path.parent.name + "-" + self.path.name
}
示例15: PersistAsyncActor
//设置package包名称以及导入依赖的类
package akka.persistence.pg.perf
import akka.actor.{Props, ActorLogging}
import akka.persistence.PersistentActor
import akka.persistence.pg.perf.Messages.{Alter, Altered}
class PersistAsyncActor(override val persistenceId: String) extends PersistentActor with ActorLogging {
override def receiveRecover: Receive = { case _ => }
override def receiveCommand: Receive = {
case Alter(txt) =>
val created = System.currentTimeMillis()
val events = 1 to 10 map { i =>
Altered(s"${txt}_$i", created)
}
persistAllAsync(events) { _ => sender ! txt }
}
}
object PersistAsyncActor {
def props(persistenceId: String) = Props(new PersistAsyncActor(persistenceId))
}