当前位置: 首页>>代码示例>>Scala>>正文


Scala RecoveryCompleted类代码示例

本文整理汇总了Scala中akka.persistence.RecoveryCompleted的典型用法代码示例。如果您正苦于以下问题:Scala RecoveryCompleted类的具体用法?Scala RecoveryCompleted怎么用?Scala RecoveryCompleted使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了RecoveryCompleted类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
  }
} 
开发者ID:Passarinho4,项目名称:reactive-lab4,代码行数:41,代码来源:Counter.scala

示例2: processCommand

//设置package包名称以及导入依赖的类
package com.benoj.janus.behavior

import akka.actor.Actor._
import akka.persistence.RecoveryCompleted
import cats.data.Xor
import com.benoj.janus.Events.{JanusEvent, _}
import com.benoj.janus.PersistentLoggingActor


trait  CommandProcess {
  def processCommand: Receive = PartialFunction.empty
}

trait JanusEventProcessing extends CommandProcess { self: PersistentLoggingActor =>
  override def persistenceId: String = this.self.path.name

  def processEvent: ReceiveEvent = PartialFunction.empty

  override def receiveRecover: Receive = {
    case event: JanusEvent => processEvent(event)
    case RecoveryCompleted => log.info("Recovered Actor")
  }

  def processEventAndNotifySender(event: JanusEvent): Unit = processEvent(event) match {
    case Xor.Right(_) =>
      sender() ! "OK"
    case Xor.Left(e) =>
      sender() ! e
  }

  override def receiveCommand: Receive = processCommand

} 
开发者ID:benoj,项目名称:janus,代码行数:34,代码来源:JanusEventProcessing.scala

示例3: 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")
  }
} 
开发者ID:irishshagua,项目名称:dublin-pubs-shite-talking,代码行数:34,代码来源:ShiteTalker.scala

示例4: Borrower

//设置package包名称以及导入依赖的类
package com.abstractcode.bathurst

import akka.actor.{ActorLogging, Props, ReceiveTimeout}
import akka.cluster.sharding.ShardRegion
import akka.cluster.sharding.ShardRegion.Passivate
import akka.persistence.{PersistentActor, RecoveryCompleted}


class Borrower extends PersistentActor with ActorLogging {

  import Borrower._

  override def persistenceId: String = "borrower-" + self.path.name

  override def receiveRecover = {
    case e: BorrowerEvent => updateState(e)
    case RecoveryCompleted =>  }

  override def receiveCommand = {
    case CreateBorrower(catalogId, borrowerId, name) => persist(BorrowerCreated(catalogId, borrowerId, name))(e => {
      updateState(e)
      sender() ! e
    })
    case ReceiveTimeout ? context.parent ! Passivate(stopMessage = Stop)
    case Stop ? context.stop(self)
  }

  def updateState(e: BorrowerEvent) = e match {
    case i: BorrowerCreated =>
  }
}

object Borrower {
  sealed trait BorrowerCommand {
    val catalogId: Int
    val borrowerId: Int
  }

  final case class CreateBorrower(catalogId: Int, borrowerId: Int, name: String) extends BorrowerCommand

  sealed trait BorrowerEvent {
    val borrowerId: Int
  }

  final case class BorrowerCreated(catalogId: Int, borrowerId: Int, name: String) extends BorrowerEvent

  val extractEntityId: ShardRegion.ExtractEntityId = {
    case i: BorrowerCommand => (s"${i.catalogId}_${i.borrowerId}", i)
  }

  val numberOfShards = 128

  val extractShardId: ShardRegion.ExtractShardId = {
    case i: BorrowerCommand => math.abs(s"${i.catalogId}_${i.borrowerId}".hashCode % numberOfShards).toString
  }

  def props() = Props(new Borrower())
} 
开发者ID:ColinScott,项目名称:bathurst,代码行数:59,代码来源:Borrower.scala

示例5: 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

示例6: StockPersistenceActor

//设置package包名称以及导入依赖的类
package com.packt.chapter6

import akka.actor.{ActorLogging, Props}
import akka.persistence.{PersistentActor, RecoveryCompleted}

object StockPersistenceActor {
  def props(stockId: String) = Props(new StockPersistenceActor(stockId))
}

class StockPersistenceActor(stockId: String) extends PersistentActor with ActorLogging {
  override val persistenceId = stockId

  var state = StockHistory()
  def updateState(event: ValueAppended) = state = state.update(event)

  val receiveRecover: Receive = {
    case evt: ValueAppended => updateState(evt)
    case RecoveryCompleted => log.info(s"Recovery completed. Current state: $state")
  }

  val receiveCommand: Receive = {
    case ValueUpdate(value) => persist(ValueAppended(StockValue(value)))(updateState)
    case "print" => log.info(s"Current state: $state")
  }

  override def postStop() = log.info(s"Stopping [${self.path}]")
} 
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:28,代码来源:StockPersistenceActor.scala

示例7: Persist

//设置package包名称以及导入依赖的类
package com.sbuljat.mailgunner.queue

import java.util.UUID

import akka.actor.{ActorLogging, Actor}
import akka.persistence.{RecoveryCompleted, PersistentActor}
import com.sbuljat.mailgunner.model.{SendMessageResponse, SendMessageRequest}
import com.sbuljat.mailgunner.service.MailgunService



case class Persist(event:Event)
case class Event(request:SendMessageRequest, response:Option[SendMessageResponse]=None)

class QueueActor extends PersistentActor with ActorLogging{
  override def persistenceId = "mail-queue"

  implicit def executionContext = context.dispatcher

  val mailgun = new MailgunService()

  var state = scala.collection.mutable.MutableList[Event]()

  val receiveRecover:Receive = {
    case event:Event =>
      state += event
    case RecoveryCompleted =>
      state.groupBy(e => e.request.id).foreach{ case (id,events) =>
        events.toList match {
          case first :: second :: Nil if(second.response.nonEmpty || first.response.nonEmpty) =>
            log.info(s"[RECOVERY] Fully processed event ${first.request.id}")
          case first :: Nil =>
            log.info(s"[RECOVERY] [${first.request.id}] Unprocessed request ${first.request}")
            mailgun.send(first.request).map(res =>
              self ! Persist(Event(res.request, Some(res)))
            )
          case _ =>
        }
      }

  }

  val receiveCommand:Receive = {
    case cmd:Persist =>
      persistAsync(cmd.event){e =>
        log.info(s"[COMMAND] Persisted ${e.request.id}")
      }
    case event:Event =>
      persistAsync(event){e =>
        sender() ! SendMessageResponse(true, s"Message has been queued under id ${e.request.id}", event.request)
        mailgun.send(event.request).map(res =>
          if(res.success){
            self ! Persist(Event(res.request, Some(res)))
          }else{
            log.warning(s"[COMMAND] Mailgun request ${res.request.id} failed")
          }
        )
      }
  }

} 
开发者ID:sbuljat,项目名称:mailgunner,代码行数:62,代码来源:QueueActor.scala

示例8: AbstractServerDataStructureFactory

//设置package包名称以及导入依赖的类
package de.tu_berlin.formic.common.server.datastructure

import akka.actor.{ActorLogging, Props}
import akka.persistence.{PersistentActor, RecoveryCompleted}
import de.tu_berlin.formic.common.DataStructureInstanceId
import de.tu_berlin.formic.common.datastructure.DataStructureName
import de.tu_berlin.formic.common.message.CreateRequest

import scala.reflect.ClassTag


//Why the ClassTag? See http://stackoverflow.com/questions/18692265/no-classtag-available-for-t-not-for-array
abstract class AbstractServerDataStructureFactory[T <: AbstractServerDataStructure : ClassTag] extends PersistentActor with ActorLogging {

  override def persistenceId: String = name.name

  val receiveCommand: Receive = {
    case req: CreateRequest =>
      val logText = s"Factory for $name received CreateRequest: $req"
      log.debug(logText)
      val newDataType = context.actorOf(Props(create(req.dataStructureInstanceId)), req.dataStructureInstanceId.id)
      persist(req) { request =>
        sender ! NewDataStructureCreated(request.dataStructureInstanceId, newDataType)
      }
  }

  val receiveRecover: Receive = {
    case CreateRequest(_, dataStructureInstanceId, _) =>
      context.actorOf(Props(create(dataStructureInstanceId)), dataStructureInstanceId.id)
    case RecoveryCompleted =>
      val logText = s"Data type factory $name recovered"
      log.info(logText)
  }

  def create(dataStructureInstanceId: DataStructureInstanceId): T

  val name: DataStructureName
} 
开发者ID:rbraeunlich,项目名称:formic,代码行数:39,代码来源:AbstractServerDataStructureFactory.scala

示例9: Util

//设置package包名称以及导入依赖的类
package com.github.dnvriend

import java.util.UUID

import akka.actor.{ActorLogging, ActorSystem, Props}
import akka.persistence.{PersistentActor, RecoveryCompleted}

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import scala.util.Try

object Util {
  def getProperty(key: String, default: String): String = Try(System.getProperty(key)).toOption.flatMap(Option(_)).getOrElse(default)
}

class Persister(val persistenceId: String, max: Int = Util.getProperty("max", "10").toInt)(implicit ec: ExecutionContext) extends PersistentActor with ActorLogging {
  context.system.scheduler.schedule(0.seconds, 300.millis, self, "FOO")

  var counter = 0

  override val receiveRecover: Receive = {
    case RecoveryCompleted => log.debug("Recovery completed: lastSeqNr: {}", lastSequenceNr)
    case msg: String =>
      log.debug("Recovering with: {}", msg)
      counter += 1
    case unknown => log.debug("Unknown msg: {}", unknown)
  }

  override val receiveCommand: Receive = {
    case _ if counter < max =>
      persist(UUID.randomUUID().toString) { _ => counter += 1; () }
    case _ =>
      log.debug("Stopping...")
      context.stop(self)
      context.system.terminate()
  }

  override def postStop(): Unit = {
    log.debug("Stopped!")
  }
}

object Main extends App {
  implicit val system = ActorSystem()
  implicit val ec = system.dispatcher
  system.actorOf(Props(new Persister("abcdefg")))

  println("This is v2.6.3")
} 
开发者ID:dnvriend,项目名称:akka22to26,代码行数:50,代码来源:Main.scala

示例10: Util

//设置package包名称以及导入依赖的类
package com.github.dnvriend

import java.util.UUID

import akka.actor.{ActorLogging, ActorSystem, Props}
import akka.persistence.{PersistentActor, RecoveryCompleted}

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import scala.util.Try

object Util {
  def getProperty(key: String, default: String): String = Try(System.getProperty(key)).toOption.flatMap(Option(_)).getOrElse(default)
}

class Persister(val persistenceId: String, max: Int = Util.getProperty("max", "10").toInt)(implicit ec: ExecutionContext) extends PersistentActor with ActorLogging {
  context.system.scheduler.schedule(0.seconds, 300.millis, self, "FOO")

  var counter = 0

  override val receiveRecover: Receive = {
    case RecoveryCompleted => log.debug("Recovery completed: lastSeqNr: {}", lastSequenceNr)
    case msg: String =>
      log.debug("Recovering with: {}", msg)
      counter += 1
    case unknown => log.debug("Unknown msg: {}", unknown)
  }

  override val receiveCommand: Receive = {
    case _ if counter < max =>
      persist(UUID.randomUUID().toString) { _ => counter += 1; () }
    case _ =>
      log.debug("Stopping...")
      context.stop(self)
      context.system.terminate()
  }

  override def postStop(): Unit = {
    log.debug("Stopped!")
  }
}

object Main extends App {
  implicit val system = ActorSystem()
  implicit val ec = system.dispatcher
  system.actorOf(Props(new Persister("abcdefg")))

  println("This is v2.2.8")
} 
开发者ID:dnvriend,项目名称:akka22to26,代码行数:50,代码来源:Main.scala

示例11: CombatHandler

//设置package包名称以及导入依赖的类
package net.cucumbersome.rpgRoller.warhammer.combat

import akka.actor.{ActorLogging, Props}
import akka.persistence.{PersistentActor, RecoveryCompleted}
import net.cucumbersome.rpgRoller.warhammer.player.CombatActor

class CombatHandler(actorId: String) extends PersistentActor with ActorLogging{
  import CombatHandler._
  override def persistenceId: String = actorId
  private var state: Map[String, Combat] = Map()

  override def receiveRecover: Receive = {
    case evt: CombatEvent => handleEvent(evt)
    case RecoveryCompleted => log.debug("Recovery completed!")
  }

  override def receiveCommand: Receive = {
    case InitCombat(id, actors) => persist(CombatInitialized(id, actors))(handleEvent)
    case AddActors(id, actors) => persist(ActorsAdded(id, actors))(handleEvent)
    case RemoveActors(id, actors) => persist(ActorsRemoved(id, actors))(handleEvent)
    case GetCombat(id) => sender ! GetCombatResponse(id, getCombat(id))
  }

  private def handleEvent(evt: CombatEvent): Unit = evt match {
    case CombatInitialized(id, actors) =>
      val (newState, _) = Combat.addActor(actors).run(Combat.empty).value
      state = state + (id -> newState)
    case ActorsAdded(id, actors) =>
      val (newState, _) = Combat.addActor(actors).run(getCombat(id)).value
      state = state + (id -> newState)
    case ActorsRemoved(id, actorsToBeRemoved) =>
      val (newState, _) = Combat.removeActors(actorsToBeRemoved).run(getCombat(id)).value
      state = state + (id -> newState)
  }

  private def getCombat(id: String): Combat = {
    state.getOrElse(id, Combat.empty)
  }
}

object CombatHandler{
  def props(actorId: String): Props = Props(new CombatHandler(actorId))

  sealed trait CombatEvent
  case class CombatInitialized(id: String, actors: List[CombatActor]) extends CombatEvent
  case class ActorsAdded(id: String, actors: List[CombatActor]) extends CombatEvent
  case class ActorsRemoved(id: String, actors: List[CombatActor]) extends CombatEvent

  case class InitCombat(id: String, actors: List[CombatActor])

  case class GetCombat(id: String)
  case class GetCombatResponse(id: String, combat: Combat)

  case class AddActors(id: String, actors: List[CombatActor])

  case class RemoveActors(id: String, actors: List[CombatActor])
} 
开发者ID:CucumisSativus,项目名称:rpgRollerBackend,代码行数:58,代码来源:CombatHandler.scala


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