本文整理汇总了Scala中akka.actor.FSM类的典型用法代码示例。如果您正苦于以下问题:Scala FSM类的具体用法?Scala FSM怎么用?Scala FSM使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FSM类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Disconnected
//设置package包名称以及导入依赖的类
package com.dazito.scala.akkademy.client
import akka.actor.FSM
import com.dazito.scala.akkademy.client.StateContainerTypes.RequestQueue
import com.dazito.scala.dakkabase.messages.{Connected, GetRequest, Disconnected}
sealed trait State
case object Disconnected extends State
case object Connected extends State
case object ConnectedAndPending extends State
case object Flush
case object ConnectedMsg
object StateContainerTypes {
type RequestQueue = List[GetRequest]
}
class FSMActor(address: String) extends FSM[State, RequestQueue] {
val remoteDb = context.system.actorSelection(address)
startWith(Disconnected, null)
when(Disconnected) {
case (_: Connected, container: RequestQueue) =>
if(container.headOption.isEmpty)
goto(Connected)
else
goto(ConnectedAndPending)
case (x: GetRequest, container: RequestQueue) =>
stay using(container :+ x)
}
when(Connected) {
case (x: GetRequest, container: RequestQueue) =>
goto(ConnectedAndPending) using(container :+ x)
}
when(ConnectedAndPending) {
case (Flush, container) =>
remoteDb ! container
goto(Connected) using Nil
case (x: GetRequest, container: RequestQueue) =>
stay using(container :+ x)
}
initialize()
}
示例2: handleReconnectProof
//设置package包名称以及导入依赖的类
package wow.auth.handlers
import akka.actor.FSM
import wow.auth.data.Account
import wow.auth.protocol.AuthResults
import wow.auth.protocol.packets._
import wow.auth.session.AuthSession.EventIncoming
import wow.auth.session._
import wow.auth.utils.PacketSerializer
trait ReconnectProofHandler {
this: AuthSession =>
def handleReconnectProof: StateFunction = {
case Event(EventIncoming(bits), ReconnectChallengeData(login, random)) =>
log.debug("Received reconnect proof")
val packet = PacketSerializer.deserialize[ClientReconnectProof](bits)
log.debug(packet.toString)
def reverify(sessionKey: BigInt) = srp6.reverify(login, random, packet.clientKey, packet.clientProof, sessionKey)
val account = Account.findByLogin(login)
val (nextState, authResult) = account match {
case Some(Account(_, _, _, Some(sessionKey))) if reverify(sessionKey) =>
val state: FSM.State[AuthSessionState, AuthSessionData] = goto(StateRealmlist) using RealmsListData(login)
(state, AuthResults.Success)
case _ =>
val state: FSM.State[AuthSessionState, AuthSessionData] = goto(StateFailed) using NoData
(state, AuthResults.FailUnknownAccount)
}
sendPacket(ServerReconnectProof(authResult))
nextState
}
}
示例3: PrintGreetingFSM
//设置package包名称以及导入依赖的类
package v4_fsm
import akka.actor.{Actor, FSM}
import protocol.{Goodbye, SayHello, SetGreeting}
import PrintGreetingFSM._
class PrintGreetingFSM extends Actor with FSM[State, Data] {
startWith(WaitingForGreeting, NoGreeting)
when(WaitingForGreeting) {
case Event(SetGreeting(greeting), _) =>
println("ready to say hello with " + greeting)
goto(WithGreeting) using Greeting(greeting)
case Event(SayHello(_), _) =>
println("I don't know how to greet")
stay
case Event(Goodbye, _) =>
println("You haven't even said hello")
stay
}
when(WithGreeting) {
case Event(SetGreeting(greeting), _) =>
println("ready to say hello with " + greeting)
stay using Greeting(greeting)
case Event(SayHello(who), Greeting(greeting)) =>
println(greeting + " " + who)
stay
case Event(Goodbye, _) =>
println("goodbye")
goto(WaitingForGreeting) using NoGreeting
}
}
object PrintGreetingFSM {
sealed trait State
case object WaitingForGreeting extends State
case object WithGreeting extends State
sealed trait Data
case object NoGreeting extends Data
case class Greeting(greeting: String) extends Data
}
示例4: Evolve
//设置package包名称以及导入依赖的类
package com.devdiscoveries.genalg
import akka.actor.FSM
case class Evolve(populationSize: Int, numberOfGenerations: Int)
case class Initialize(populationSize: Int, numberOfGenerations: Int)
case object Status
case class CurrentStatus[State](state: State,
numberOfGenerations: Int = 0,
currentGeneration: Int = 0)
sealed trait State
case object Idle extends State
case object Initialized extends State
case object Evolving extends State
case object Done extends State
sealed trait Data
case object Uninitialized extends Data
case class GenAlgData[Individual](population: Seq[Individual],
numberOfGenerations: Int,
currentGeneration: Int)
class GeneticAlgorithmFSM extends FSM[State, Data] {
startWith(Idle, Uninitialized)
when(Idle) {
case Event(Initialize(popSize, numGens), Uninitialized) =>
goto(Initialized)
}
when(Initialized) {
case Event(Evolve, data: GenAlgData[_]) =>
goto(Evolving)
}
when(Evolving) {
case Event(Done, data: GenAlgData[_]) =>
goto(Idle)
}
whenUnhandled{
case Event(Status, s) =>
stay replying CurrentStatus(state = stateName)
case Event(e, s) =>
log.warning("received request {} is unhandled in state {}/{}", e, stateName, s)
stay
}
initialize()
}
示例5: Uninitialized
//设置package包名称以及导入依赖的类
package auction_system.seller
import akka.actor.{Props, ActorRef, FSM}
import auction_system.auction.Auction
import auction_system.auction.Auction.AuctionEnded
import auction_system.auction_search.AuctionSearch
import auction_system.master_search.MasterSearch
import scala.concurrent.Await
import scala.concurrent.duration._
sealed trait SellerState
case object Uninitialized extends SellerState
case object Active extends SellerState
case object WithoutAuctions extends SellerState
sealed trait SellerData
case object NoData extends SellerData
case class MyAuctions(auctions: List[ActorRef]) extends SellerData
case object NoAuctions extends SellerData
object Seller {
case class Initialize(auctionNames: List[String], Notifier: ActorRef)
case class NewAuction(auctionName: String)
}
class Seller extends FSM[SellerState, SellerData] {
import Seller._
startWith(Uninitialized, NoData)
when(Uninitialized) {
case Event(Initialize(auctionNames, notifier: ActorRef), NoData) =>
// println("Seller initialized")
val auctions = for(name <- auctionNames) yield context.system.actorOf(Props[Auction], name)
for(auction <- auctions) {
context.actorSelection("../master_search") ! MasterSearch.Register(auction)
auction ! Auction.Setup(self, notifier)
}
goto(Active) using MyAuctions(auctions)
}
when(Active) {
case Event(AuctionEnded(auction), t: MyAuctions) =>
t.auctions.filterNot(elem => elem == auction)
if(t.auctions.nonEmpty)
stay using t
else
goto(WithoutAuctions) using NoAuctions
case Event(NewAuction(auctionName), t: MyAuctions) =>
stay using new MyAuctions(context.actorOf(Props[Auction], auctionName) :: t.auctions)
}
when(WithoutAuctions, stateTimeout = 2 seconds) {
case Event(NewAuction(name), NoAuctions) =>
goto(Active) using MyAuctions(List(context.system.actorOf(Props[Auction], name)))
case Event(StateTimeout, NoAuctions) =>
stop
}
initialize()
}
示例6: Active
//设置package包名称以及导入依赖的类
package auction_system.auction_search
import akka.actor.{ActorRef, FSM}
import auction_system.auction.Auction.AuctionEnded
import scala.concurrent.duration._
sealed trait AuctionSearchState
case object Active extends AuctionSearchState
case object WithoutAuctions extends AuctionSearchState
sealed trait AuctionSearchData
case class MyAuctions(auctions: List[ActorRef]) extends AuctionSearchData
case object NoAuctions extends AuctionSearchData
object AuctionSearch {
case class NewAuction(auction: ActorRef)
case class Find(auctionName: String)
case class SearchResult(auctions: List[ActorRef])
}
class AuctionSearch extends FSM[AuctionSearchState, AuctionSearchData] {
import AuctionSearch._
startWith(WithoutAuctions, NoAuctions)
when(Active) {
case Event(AuctionEnded(auction), t: MyAuctions) =>
t.auctions.filterNot(elem => elem == auction)
if(t.auctions.nonEmpty)
stay using t
else
goto(WithoutAuctions) using NoAuctions
case Event(NewAuction(auction), t: MyAuctions) =>
// println(s"New auction ${auction.path.name} registered")
stay using MyAuctions(auction :: t.auctions)
case Event(Find(name), t: MyAuctions) =>
sender ! SearchResult(t.auctions.filter(elem => elem.path.name == name))
stay using t
}
when(WithoutAuctions, stateTimeout = 2 seconds) {
case Event(NewAuction(auction), NoAuctions) =>
// println(s"New auction ${auction.path.name} registered")
goto(Active) using MyAuctions(List(auction))
case Event(StateTimeout, NoAuctions) =>
stop
}
initialize()
}
示例7: Channel
//设置package包名称以及导入依赖的类
package com.mildlyskilled.actors
import akka.actor.FSM
import com.mildlyskilled.protocol.Channel._
import com.mildlyskilled.protocol.Message._
class Channel extends FSM[State, Data] {
startWith(Idle, ChannelState(Nil))
when(Idle) {
case Event(RegisterUser(p), [email protected](participants)) =>
sender ! Info(s"${p.path.name} registered with ${self.path.name}")
p ! Info(s"${p.path.name} registered with ${self.path.name}")
goto(Active) using s.copy(participants = p :: participants)
case Event(Start, _) =>
goto(Active)
}
when(Active) {
case Event(RegisterUser(p), [email protected](participants)) =>
sender ! Info(s"${p.path.name} registered with ${self.path.name}")
p ! Info(s"${p.path.name} registered with ${self.path.name}")
stay using s.copy(participants = p :: participants)
case Event(RegisteredUsers, [email protected](participants)) =>
sender ! RegisteredUsers(participants.map(a => a.path.name))
log.info(s"Sending list to ${sender.path.name}")
stay using s
case Event(RemoveUser(user), [email protected](participants)) =>
user ! Info(s"Removing ${user.path.name} from ${self.path.name}")
stay using s.copy(participants = participants.filterNot((x) => x == user))
}
onTransition {
case _ -> Active =>
log.info(Console.BLUE_B + "Channel going ACTIVE" + Console.RESET)
case _ -> Idle =>
log.info(Console.BLUE_B + "Channel going IDLE" + Console.RESET)
}
}
示例8: Client
//设置package包名称以及导入依赖的类
package com.mildlyskilled.actors
import akka.actor.FSM
import com.mildlyskilled.core.ConsoleAction
import com.mildlyskilled.protocol.Client._
import com.mildlyskilled.protocol.Message._
class Client extends FSM[State, Data] {
startWith(Idle, ClientData(self.path.name, None, Nil))
when(Idle) {
case Event(Connect(serverRef), cd: ClientData) =>
log.info(Console.GREEN + s"Sent register message to server at ${serverRef.path.name}" + Console.RESET)
goto(Active) using cd.copy(server = Some(serverRef))
case Event(AuthenticationStatus(x), cd: ClientData) =>
goto(Active)
case Event(Info(msg), _) =>
log.info(Console.YELLOW + msg + Console.RESET)
stay()
}
when(Active) {
case Event(Login(username, password), cd: ClientData) =>
cd.server match {
case Some(server) => server ! Login(username, password)
case None => log.warning("We are not registered on any server")
}
stay()
case Event(JoinChannel(channel), _) =>
stay()
case Event(AuthenticationStatus(x), cd: ClientData) =>
stay()
case Event(Connect(serverRef), cd: ClientData) =>
log.info(Console.GREEN + s"Sent register message to server at ${serverRef.path.name}" + Console.RESET)
goto(Active) using cd.copy(server = Some(serverRef))
case Event(Stop, _) =>
context.stop(self)
stay() // eh?
case Event(Info(msg), _) =>
log.info(Console.YELLOW + msg + Console.RESET)
stay()
case Event(RegisteredUsers(listOfUsers), _) =>
ConsoleAction.outputList(listOfUsers, "Users")
stay()
case Event(ChannelList(listOfChannels), _) =>
ConsoleAction.outputList(listOfChannels, "Channels")
stay()
}
onTransition {
case _ -> Active =>
log.info(Console.BLUE + "Client going ACTIVE" + Console.RESET)
case _ -> Idle =>
log.info(Console.BLUE + "Client going IDLE" + Console.RESET)
}
}
示例9: SignalChangeFSMActor
//设置package包名称以及导入依赖的类
package net.petitviolet.fsm_actor_ex.fsm
import akka.actor.{ FSM, Actor }
import net.petitviolet.fsm_actor_ex.fsm.SignalData._
class SignalChangeFSMActor extends Actor with FSM[SignalState, SignalData] {
startWith(Red, RedData)
private def stayWithLogging = {
println(s"retain: $stateData")
stay
}
private def gotoWithLogging(d: Any)(s: SignalState) = {
println(s"current => $stateData, d => $d")
goto(s)
}
when(Green) {
case Event(ChangeSignal, _) => goto(Yellow) using YellowData
case Event(RetainSignal, _) => stay
}
when(Yellow) {
case Event(ChangeSignal, _) => goto(Red) using RedData
case Event(RetainSignal, _) => stay
}
when(Red) {
case Event(ChangeSignal, _) => goto(Green) using GreenData
case Event(RetainSignal, _) => stay
}
onTransition {
case Green -> Yellow =>
println(s"WARN! green -> yellow: $stateData")
case Yellow -> Red =>
println(s"CAUTION! yellow -> red: $stateData")
case Red -> Green =>
println(s"OK! red -> green: $stateData")
}
onTermination {
case StopEvent(_, _, _) =>
println("Shutting down FSM...")
}
initialize()
}
示例10: TrafficLightFSM
//设置package包名称以及导入依赖的类
package com.packt.chapter10
import java.util.Date
import akka.actor.{Actor, ActorLogging, ActorRef, FSM}
import TrafficLightFSM._
import scala.concurrent.duration._
object TrafficLightFSM {
sealed trait TrafficLightState
case object Green extends TrafficLightState
case object Yellow extends TrafficLightState
case object Red extends TrafficLightState
sealed trait Data
case class Countdown(i: Int) extends Data
//Events
case object Tick
case class ReportChange(to: TrafficLightState, date: Date)
}
class TrafficLightFSM(changesSubscriber: ActorRef) extends Actor with ActorLogging with FSM[TrafficLightState, Data]{
import context.dispatcher
trafficLightState(Green, Yellow, 2)
trafficLightState(Yellow, Red, 4)
trafficLightState(Red, Green, 8)
startWith(Green, Countdown(8))
initialize()
scheduleTick()
onTransition {
case Green -> Yellow => changesSubscriber ! ReportChange(Yellow, new Date())
case Yellow -> Red => changesSubscriber ! ReportChange(Red, new Date())
case Red -> Green => changesSubscriber ! ReportChange(Green, new Date())
}
private def scheduleTick() = {
context.system.scheduler.scheduleOnce(1 second, self, Tick)
}
private def trafficLightState(
trafficLightState: TrafficLightState,
nextTrafficLightState: TrafficLightState,
totalSecondsNextState: Int) = {
when(trafficLightState) {
case Event(Tick, Countdown(i)) if i != 0 =>
scheduleTick()
log.info(s"Current state [$trafficLightState]. Countdown: [$i].")
stay using Countdown(i - 1)
case Event(Tick, Countdown(i)) if i == 0 =>
scheduleTick()
log.info(s"Changing from $trafficLightState to $nextTrafficLightState.")
goto(nextTrafficLightState) using Countdown(totalSecondsNextState)
}
}
}
示例11: ItemData
//设置package包名称以及导入依赖的类
package com.project.production
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.FSM
import akka.actor.FSM._
import akka.actor.Props
import scala.collection.immutable.Queue
case class ItemData(val erpData: ERPData, val specData: SpecData, val prodData: Queue[_])
class Item extends Actor {
val fsm: ActorRef = context.actorOf(Props[ItemFSM])
var erpData: Option[ERPData] = None
var specData: Option[SpecData] = None
var prodData: Option[Queue[_]] = None
implicit val formats = Serialization.formats(NoTypeHints)
def receive = {
case (x: ProdEvent, y: ProdData) => fsm ! (x, y)
case x: ERPData => erpData = Some(x)
case x: SpecData => {
specData = Some(x)
trySubmit()
}
case x: Queue[_] => prodData = Some(x)
}
def itemData: ItemData = {
val item = for {
e <- erpData
s <- specData
p <- prodData
} yield ItemData(e, s, p)
item.get
}
def serialize(item: ItemData): String = {
write(item)
}
def trySubmit() {
erpData.isDefined && specData.isDefined && prodData.isDefined match {
case true => context.parent ! serialize(itemData)
case _ => ()
}
}
}
示例12: ComposedStateFunction
//设置package包名称以及导入依赖的类
package beam.agentsim.agents
import akka.actor.FSM
import beam.agentsim.agents.BeamAgent.{BeamAgentInfo, BeamAgentState}
import beam.agentsim.agents.PersonAgent.PersonData
object ComposedStateFunction{
def apply(partialFunction: PartialFunction[FSM.Event[_] ,FSM.State[BeamAgentState,BeamAgentInfo[PersonData]]]) =
new ComposedStateFunction(partialFunction)
}
class ComposedStateFunction(partialFunction: PartialFunction[FSM.Event[_] ,FSM.State[BeamAgentState,BeamAgentInfo[PersonData]]]) {
var pf = partialFunction
def add(partialFunction: PartialFunction[FSM.Event[_] ,FSM.State[BeamAgentState,BeamAgentInfo[PersonData]]]): Unit ={
pf = pf orElse partialFunction
}
}
示例13: logDepth
//设置package包名称以及导入依赖的类
package com.pagerduty.scheduler.akka
import akka.actor.{FSM, LoggingFSM}
trait ExtendedLoggingFSM[State, Data] extends LoggingFSM[State, Data] {
override def logDepth = 10
onTermination {
case StopEvent(FSM.Failure(_), state, data) => {
val lastEvents = getLog.mkString("\n\t")
// This is for low-level actor debugging, so we are not using Scheduler.Logging.
log.error(s"Failure in $state with $data.\nEvent log:\n\t$lastEvents")
}
}
}
示例14: sendHeartBeat
//设置package包名称以及导入依赖的类
package com.art4ul.raft.actor
import java.util.concurrent.TimeUnit
import akka.actor.FSM
import com.art4ul.raft.ExecutionConfig
import com.art4ul.raft.state.{CommandModel, Leader, Data, State}
import com.art4ul.raft.utils.StateLogger
import com.art4ul.scrafty.protocol.{AppendEntryRequest, Response, NewCommandRequest, AppendEntryResponse}
import scala.concurrent.duration.FiniteDuration
trait LeaderLogic extends StateLogger {
selfRef: FSM[State, Data] with CommonRaft=>
val heartBeatTimeout = FiniteDuration(ExecutionConfig.heartBeatTimeoutMs, TimeUnit.MILLISECONDS)
when(Leader, stateTimeout = heartBeatTimeout) {
case Event([email protected], data: Data) =>
logState(s"message:$msg")
sendHeartBeat(data.currentTerm)
stay
case Event(response: AppendEntryResponse, data: Data) =>
logState(s"message:$response")
stay
case Event(msg: NewCommandRequest, data: Data) =>
val connectionRef = sender
val newLog = data.log :+ CommandModel(data.currentTerm, msg.command, connectionRef)
stay() using (data.copy(log = newLog))
}
def sendHeartBeat(term: Int): Unit = {
val responseHandler: Response => Unit = response => self ! response
broadcast(AppendEntryRequest(term, id), responseHandler)
}
}
示例15:
//设置package包名称以及导入依赖的类
package com.art4ul.raft.actor
import akka.actor.FSM
import akka.actor.FSM.Event
import com.art4ul.raft.state.{State, Candidate, Data, Follower}
import com.art4ul.raft.utils.StateLogger
import com.art4ul.scrafty.protocol._
trait FollowerLogic extends StateLogger {
selfRef: FSM[State, Data] with CommonRaft=>
when(Follower, electionTimeout) {
case Event(msg: AppendEntryRequest, data: Data) =>
logState(s"message:$msg")
handleRequest(msg) {
case term if (term == data.currentTerm) => stay -> AppendEntryResponse(data.currentTerm, true)
case term if (term >= data.currentTerm) =>
val newData = data.copy(currentTerm = term, votedFor = Some(msg.leaderId))
stay.using(newData) -> AppendEntryResponse(term, true)
case _ => stay() -> AppendEntryResponse(data.currentTerm, false)
}
case Event([email protected], data: Data) =>
logState(s"message:$msg")
val newData = data.copy(currentTerm = data.currentTerm + 1,
votedFor = Some(id),
votes = 1)
goto(Candidate) using newData
case Event(msg: VoteRequest, data: Data) =>
logState(s"message:$msg")
handleRequest(msg) {
case term if (term > data.currentTerm) || (term == data.currentTerm && data.votedFor.isEmpty) =>
val newData = data.copy(currentTerm = term,
votedFor = Some(msg.candidateId),
votes = 0)
stay.using(newData) -> VoteResponse(term, true)
case _ => stay -> VoteResponse(data.currentTerm, false)
}
case Event(msg: NewCommandRequest, data: Data) =>
sender ! NewCommandResponse(redirect = true, redirectTo = data.votedFor)
stay()
}
}