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


Scala ReceiveTimeout类代码示例

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


在下文中一共展示了ReceiveTimeout类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: passivate

//设置package包名称以及导入依赖的类
package actors.es

import akka.actor.{ActorLogging, PoisonPill, Actor, ReceiveTimeout}
import akka.cluster.sharding.ShardRegion.Passivate

trait Passivation extends ActorLogging {
  this: Actor =>

  protected def passivate(receive: Receive): Receive = receive.orElse {
    // tell parent actor to send us a poisinpill
    case ReceiveTimeout =>
      log.info(s" $self ReceiveTimeout: passivating. ")
      context.parent ! Passivate(stopMessage = PoisonPill)

    // stop
    case PoisonPill =>
      log.info(s" $self PoisonPill")
      context.stop(self)
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:21,代码来源:Passivation.scala

示例2: LookupActor

//设置package包名称以及导入依赖的类
package sample.remote.calculator

import scala.concurrent.duration._
import akka.actor.Actor
import akka.actor.ActorIdentity
import akka.actor.ActorRef
import akka.actor.Identify
import akka.actor.ReceiveTimeout
import akka.actor.Terminated

class LookupActor(path: String) extends Actor {

  sendIdentifyRequest()

  def sendIdentifyRequest(): Unit = {
    context.actorSelection(path) ! Identify(path)
    import context.dispatcher
    context.system.scheduler.scheduleOnce(3.seconds, self, ReceiveTimeout)
  }

  def receive = identifying

  def identifying: Actor.Receive = {
    case ActorIdentity(`path`, Some(actor)) =>
      context.watch(actor)
      context.become(active(actor))
    case ActorIdentity(`path`, None) => println(s"Remote actor not available: $path")
    case ReceiveTimeout              => sendIdentifyRequest()
    case _                           => println("Not ready yet")
  }

  def active(actor: ActorRef): Actor.Receive = {
    case op: MathOp => actor ! op
    case result: MathResult => result match {
      case AddResult(n1, n2, r) =>
        printf("Add result: %d + %d = %d\n", n1, n2, r)
      case SubtractResult(n1, n2, r) =>
        printf("Sub result: %d - %d = %d\n", n1, n2, r)
    }
    case Terminated(`actor`) =>
      println("Calculator terminated")
      sendIdentifyRequest()
      context.become(identifying)
    case ReceiveTimeout =>
    // ignore

  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:49,代码来源:LookupActor.scala

示例3: FactorialFrontend

//设置package包名称以及导入依赖的类
package sample.cluster.factorial

import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorSystem
import akka.actor.Props
import akka.cluster.Cluster
import akka.routing.FromConfig
import akka.actor.ReceiveTimeout

//#frontend
class FactorialFrontend(upToN: Int, repeat: Boolean) extends Actor with ActorLogging {

  val backend = context.actorOf(FromConfig.props(),
    name = "factorialBackendRouter")

  override def preStart(): Unit = {
    sendJobs()
    if (repeat) {
      context.setReceiveTimeout(10.seconds)
    }
  }

  def receive = {
    case (n: Int, factorial: BigInt) =>
      if (n == upToN) {
        log.debug("{}! = {}", n, factorial)
        if (repeat) sendJobs()
        else context.stop(self)
      }
    case ReceiveTimeout =>
      log.info("Timeout")
      sendJobs()
  }

  def sendJobs(): Unit = {
    log.info("Starting batch of factorials up to [{}]", upToN)
    1 to upToN foreach { backend ! _ }
  }
}
//#frontend

object FactorialFrontend {
  def main(args: Array[String]): Unit = {
    val upToN = 200

    val config = ConfigFactory.parseString("akka.cluster.roles = [frontend]").
      withFallback(ConfigFactory.load("factorial"))

    val system = ActorSystem("ClusterSystem", config)
    system.log.info("Factorials will start when 2 backend members in the cluster.")
    //#registerOnUp
    Cluster(system) registerOnMemberUp {
      system.actorOf(Props(classOf[FactorialFrontend], upToN, true),
        name = "factorialFrontend")
    }
    //#registerOnUp
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:62,代码来源:FactorialFrontend.scala

示例4: ControllerActor

//设置package包名称以及导入依赖的类
package org.remote.app.controller

import akka.actor.{Actor, ActorIdentity, ActorRef, Identify, Props, ReceiveTimeout, Terminated}
import org.remote.app.messaging.Action
import org.remote.app.sender.ManagerActor

import scala.concurrent.duration._

object ControllerActor {
  def props(remoteHost: String): Props = {
    Props(classOf[ControllerActor], remoteHost)
  }

  def actorName(host: String) = s"${host}controller"
}
class ControllerActor(remoteHost: String) extends Actor {

  val remoteActorPath = s"akka.tcp://${context.system.name}@$remoteHost/user/${ManagerActor.actorName}"

  def resolve(): Unit = {
    context.actorSelection(remoteActorPath) ! Identify(remoteActorPath)
    import context.dispatcher
    context.system.scheduler.scheduleOnce(10.seconds, self, ReceiveTimeout)
  }

  resolve()

  override def receive: Receive = identifying

  def identifying: Receive = {
    case ActorIdentity(`remoteActorPath`, Some(actor)) =>
      context.watch(actor)
      println(s"ActorIdentity was received from ${actor.path}")
      context become active(actor)
    case ActorIdentity(_, None) => println(s"Remote actor not available $remoteActorPath")
    case ReceiveTimeout         => resolve()
    case a                      => println(s"Not ready yet for $a")
  }

  def active(actor: ActorRef): Receive = {
    case ac: Action =>
      println(ac)
      actor ! ac
    case Terminated(`actor`) =>
      println(s"${actor.path} was terminated")
      resolve()
      context.become(identifying)
    case ReceiveTimeout => //Ignore
  }
} 
开发者ID:ayuzhanin,项目名称:test-akka,代码行数:51,代码来源:ControllerActor.scala

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

} 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:39,代码来源:HmdaPersistentActor.scala

示例6: ShardedIdRouterProtocol

//设置package包名称以及导入依赖的类
package org.tanukkii.reactive.snowflake

import akka.actor.{Props, ReceiveTimeout}
import akka.cluster.sharding.ShardRegion
import akka.cluster.sharding.ShardRegion.Passivate

object ShardedIdRouterProtocol {
  case object StopSending
}

class ShardedIdRouter extends IdRouter {
  import ShardedIdRouterProtocol._

  override def unhandled(msg: Any) = msg match {
    case ReceiveTimeout =>
      context.parent ! Passivate(stopMessage = StopSending)
    case StopSending => context.stop(self)
    case other => super.unhandled(other)
  }
}

object ShardedIdRouter {
  import IdRouterProtocol._

  def props: Props = Props(new ShardedIdRouter)

  def name: String = "IdRouter"

  val shardName: String = "IdRouter"

  val idExtractor: ShardRegion.ExtractEntityId = {
    case [email protected](datacenterId, workerId) => (s"$datacenterId-$workerId", cmd)
  }

  val shardResolver: ShardRegion.ExtractShardId = {
    case [email protected](datacenterId, workerId) => s"${datacenterId % 32}-${workerId % 32}"
  }
} 
开发者ID:TanUkkii007,项目名称:reactive-snowflake,代码行数:39,代码来源:ShardedIdRouter.scala

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

示例8: SocialMediaStalker

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

import akka.actor.{Actor, ActorLogging, ActorRef, ReceiveTimeout}
import com.packt.chapter10.SocialMediaAggregator.{Report, StartFetching, StopFetching}

import scala.collection.mutable
import scala.concurrent.duration._

class SocialMediaStalker(aggregator: ActorRef, userId: String) extends Actor with ActorLogging {
  import context.dispatcher

  context.setReceiveTimeout(10 seconds)

  val counts = mutable.Map.empty[String, Int].withDefaultValue(0)

  override def preStart() = {
    log.info("Politely asking to aggregate")
    aggregator ! StartFetching(userId, 1 second)
    context.system.scheduler.scheduleOnce(5 second, aggregator, StopFetching(userId))
  }

  override def postStop() = {
    log.info(s"Stopping. Overall counts for $userId: $counts")
  }

  def receive = {
    case Report(list) =>
      val stats = list.groupBy(_.socialNetwork).mapValues(_.map(_.posts.size).sum)
      log.info(s"New report: $stats")
      stats.foreach(kv => counts += kv._1 -> (counts(kv._1) + kv._2))
    case ReceiveTimeout =>
      context.stop(self)
  }
} 
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:35,代码来源:SocialMediaStalker.scala

示例9: AuthorListing

//设置package包名称以及导入依赖的类
package sample.blog

import scala.collection.immutable
import scala.concurrent.duration._
import akka.actor.ActorLogging
import akka.actor.Props
import akka.actor.PoisonPill
import akka.actor.ReceiveTimeout
import akka.cluster.sharding.ShardRegion
import akka.cluster.sharding.ShardRegion.Passivate
import akka.persistence.PersistentActor

object AuthorListing {

  def props(): Props = Props(new AuthorListing)

  case class PostSummary(author: String, postId: String, title: String)
  case class GetPosts(author: String)
  case class Posts(list: immutable.IndexedSeq[PostSummary])

  val idExtractor: ShardRegion.ExtractEntityId = {
    case s: PostSummary => (s.author, s)
    case m: GetPosts    => (m.author, m)
  }

  val shardResolver: ShardRegion.ExtractShardId = msg => msg match {
    case s: PostSummary   => (math.abs(s.author.hashCode) % 100).toString
    case GetPosts(author) => (math.abs(author.hashCode) % 100).toString
  }

  val shardName: String = "AuthorListing"
}

class AuthorListing extends PersistentActor with ActorLogging {
  import AuthorListing._

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

  // passivate the entity when no activity
  context.setReceiveTimeout(2.minutes)

  var posts = Vector.empty[PostSummary]

  def receiveCommand = {
    case s: PostSummary =>
      persist(s) { evt =>
        posts :+= evt
        log.info("Post added to {}'s list: {}", s.author, s.title)
      }
    case GetPosts(_) =>
      sender() ! Posts(posts)
    case ReceiveTimeout => context.parent ! Passivate(stopMessage = PoisonPill)
  }

  override def receiveRecover: Receive = {
    case evt: PostSummary => posts :+= evt

  }

} 
开发者ID:iamanandkris,项目名称:cluster-sharding-experiment,代码行数:61,代码来源:AuthorListing.scala

示例10: utils

//设置package包名称以及导入依赖的类
package nl.tradecloud.common.utils

import akka.actor.{Actor, ActorLogging, PoisonPill, ReceiveTimeout}
import akka.cluster.sharding.ShardRegion.Passivate
import akka.persistence.{SaveSnapshotFailure, SaveSnapshotSuccess}

trait ActorHelpers extends ActorLogging {
  this: Actor =>

  protected def utils(receive: Receive): Receive = receive.orElse {
    case evt: SaveSnapshotSuccess =>
      log.debug("Snapshot success!")
    case evt: SaveSnapshotFailure =>
      log.error("Snapshot failure!")
    case ReceiveTimeout =>
      log.debug("{} received timeout, passivating...", self.path.name)
      context.parent ! Passivate(stopMessage = PoisonPill)
    case Passivate(stopMessage) =>
      sender ! stopMessage
  }

  protected def unknownMessage: Receive = {
    case msg: Any =>
      log.warning("{} received unknown message {}", self.path.name, msg)
  }
} 
开发者ID:tradecloud,项目名称:tradecloud-microservices-demo,代码行数:27,代码来源:ActorHelpers.scala

示例11: LoginActor

//设置package包名称以及导入依赖的类
package com.dvisagie.vote.authentication

import akka.actor.{Actor, ReceiveTimeout}
import com.dvisagie.vote.injector.Provider

import scala.concurrent.duration._

class LoginActor(implicit provider: Provider) extends Actor {
  import LoginActor._
  context.setReceiveTimeout(5.seconds)

  def receive: Receive = {
    case request: LoginRequest =>
      sender() ! LoginResponse
      context stop self
    case ReceiveTimeout =>
      context stop self
  }

}
object LoginActor {
    case class LoginRequest(username: String, password: String)
    case class LoginResponse(token: String)
} 
开发者ID:divanvisagie,项目名称:vote,代码行数:25,代码来源:LoginActor.scala

示例12: RegistrationActor

//设置package包名称以及导入依赖的类
package com.dvisagie.vote.users

import akka.actor.{Actor, ReceiveTimeout}
import com.dvisagie.vote.injector.Provider

import scala.concurrent.duration._

class RegistrationActor(implicit provider: Provider) extends Actor {
  import RegistrationActor._
  context.setReceiveTimeout(5.seconds)


  def receive: Receive = {
    case request: UserRegistrationRequest =>
      sender() ! Unit
      context stop self
    case ReceiveTimeout =>
      context stop self
  }
}
object RegistrationActor {
  case class UserRegistrationRequest(username: String, email: String, password: String)
} 
开发者ID:divanvisagie,项目名称:vote,代码行数:24,代码来源:RegistrationActor.scala

示例13: UserControllerActor

//设置package包名称以及导入依赖的类
package com.dvisagie.vote.users

import java.util.UUID

import akka.actor.{Actor, ReceiveTimeout}
import com.dvisagie.vote.injector.Provider
import com.dvisagie.vote.repositories.UserRepository

import scala.concurrent.duration._

class UserControllerActor(implicit provider: Provider) extends Actor {
  import UserControllerActor._
  context.setReceiveTimeout(5.seconds)

  val userRepository: UserRepository = provider.userRepository

  def receive: Receive = {
    case createUserRequest: CreateUserRequest =>
      sender() ! CreationRequestResponse("message received", createUserRequest.username)
      context stop self
    case id: UUID =>
      sender() ! userRepository.getUserForId(id)
      context stop self
    case username: String =>
      sender() ! userRepository.getUserForUsername(username)
      context stop self
    case ReceiveTimeout =>
      context stop self
  }
}

object UserControllerActor {

  final case class CreateUserRequest(
    username: String,
    firstNames: String,
    lastName: String,
    email: String)

  final case class CreationRequestResponse(
    message: String,
    username: String)

  final case class UserResponse(
    username: String,
    firstNames: String,
    lastNames: String)
} 
开发者ID:divanvisagie,项目名称:vote,代码行数:49,代码来源:UserControllerActor.scala

示例14: NodeController

//设置package包名称以及导入依赖的类
package utils

import akka.actor.{Actor, ActorRef, Props, ReceiveTimeout}
import akka.remote.WireFormats.FiniteDuration

import scala.collection.mutable
import communication.{Ping, Request}

import scala.concurrent.Await
import scala.concurrent.duration._
import akka.pattern.ask

import scala.util.{Failure, Try}


private class NodeController(nodeMap: mutable.HashMap[String, ActorRef]) extends Actor {

  implicit val timeout = akka.util.Timeout(30 seconds)

  context.setReceiveTimeout(timeout.duration)

  override def receive: Receive = {
    case Request(nodeName: String) => {
      println(s"pinged by $nodeName")
      if (!nodeMap.keys.exists(_ == nodeName)) {
        nodeMap.put(nodeName, sender)
        println(s"$nodeName registered")
      } else {
        println(s"$nodeName already exists!")
      }
    }
    case ReceiveTimeout => {
      nodeMap.par.foreach { case (name, nodeRef) =>
        Try(Await.result(nodeRef.ask(Ping()), 1 second)) match {
          case Failure(_) => nodeMap.remove(name)
          case _ => ()
        }
      }
      context.setReceiveTimeout(timeout.duration)
    }
    case _ => println("Sth else has happenned")
  }
}


object NodeController {
  def props(nodeMap: mutable.HashMap[String, ActorRef]) = Props(new NodeController(nodeMap))
} 
开发者ID:mprzewie,项目名称:cloudia-client,代码行数:49,代码来源:NodeController.scala

示例15: passivate

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

import akka.actor.{PoisonPill, Actor, ReceiveTimeout}
import com.boldradius.cqrs.AuctionCommandQueryProtocol.InvalidAuctionAck
import com.boldradius.util.Logging
import akka.contrib.pattern.ShardRegion.Passivate

trait Passivation extends Logging {
  this: Actor =>

  protected def passivate(receive: Receive): Receive = receive.orElse{
    // tell parent actor to send us a poisinpill
    case ReceiveTimeout =>
      self.logDebug("ReceiveTimeout: passivating. " + _.toString)
      context.parent ! Passivate(stopMessage = PoisonPill)

    // stop
    case PoisonPill => context.stop(self.logDebug("PoisonPill" + _.toString))
  }
} 
开发者ID:ansovolt,项目名称:akka-dddd-cqrs-test,代码行数:21,代码来源:Passivation.scala


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