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

Scala FSM类代码示例

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

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



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


示例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
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:37,代码来源:ReconnectProofHandler.scala


示例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
} 
开发者ID:mcamou,项目名称:akka-fsm,代码行数:49,代码来源:PrintGreetingFSM.scala


示例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()
} 
开发者ID:hugovalk,项目名称:genetic-programming,代码行数:56,代码来源:GeneticAlgorithmFSM.scala


示例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()
} 
开发者ID:pkociepka,项目名称:reactive_scala,代码行数:61,代码来源:Seller.scala


示例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()
} 
开发者ID:pkociepka,项目名称:reactive_scala,代码行数:50,代码来源:AuctionSearch.scala


示例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)
  }
} 
开发者ID:mildlyskilled,项目名称:sIRC,代码行数:43,代码来源:Channel.scala


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

} 
开发者ID:mildlyskilled,项目名称:sIRC,代码行数:60,代码来源:Client.scala


示例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()
} 
开发者ID:petitviolet,项目名称:fsm-actor-ex,代码行数:50,代码来源:SignalChangeFSMActor.scala


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


示例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 _ => ()
        }
    }
} 
开发者ID:jlagarden,项目名称:dhbw-project-app,代码行数:54,代码来源:Item.scala


示例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
  }
} 
开发者ID:LBNL-UCB-STI,项目名称:beam,代码行数:19,代码来源:ComposedStateFunction.scala


示例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")
    }
  }
} 
开发者ID:PagerDuty,项目名称:scheduler,代码行数:17,代码来源:ExtendedLoggingFSM.scala


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

} 
开发者ID:art4ul,项目名称:scrafty,代码行数:41,代码来源:LeaderLogic.scala


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

} 
开发者ID:art4ul,项目名称:scrafty,代码行数:49,代码来源:FollowerLogic.scala


示例16:

//设置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._
import com.art4ul.raft.utils.StateLogger
import com.art4ul.scrafty.protocol.{NewCommandRequest, VoteResponse}

import scala.concurrent.duration.FiniteDuration


trait CandidateLogic extends StateLogger {
  selfRef: FSM[State, Data] with CommonRaft=>

  val electionPeriod = FiniteDuration(ExecutionConfig.electionPeriodMs, TimeUnit.MILLISECONDS)

  when(Candidate, stateTimeout =  electionPeriod) {
    case Event([email protected], data: Data) =>
      logState(s"message:$msg")
      if (isVotesReached(data.votes)) {
        val newData = data.copy(currentTerm = data.currentTerm, votedFor = Some(id), votes = 0)
        goto(Leader) using newData
      } else {
        val newData = data.copy(currentTerm = data.currentTerm, votedFor =  None, votes = 0)
        goto(Follower).forMax(electionTimeout) using newData
      }

    case Event(voteResponse: VoteResponse, data: Data) =>
      logState(s"message:$voteResponse")
      val votes = if (voteResponse.result) data.votes + 1 else data.votes
      if (isVotesReached(votes)) {
        goto(Leader) using data.copy(votes = 0)
      } else {
        stay using data.copy(votes = votes)
      }

    case Event(msg: NewCommandRequest, data: Data) => ???
  }

} 
开发者ID:art4ul,项目名称:scrafty,代码行数:43,代码来源:CandidateLogic.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala AuthInfoRepository类代码示例发布时间:2022-05-23
下一篇:
Scala configuration类代码示例发布时间: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