本文整理汇总了Scala中akka.actor.PoisonPill类的典型用法代码示例。如果您正苦于以下问题:Scala PoisonPill类的具体用法?Scala PoisonPill怎么用?Scala PoisonPill使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PoisonPill类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: OrderProcessor
//设置package包名称以及导入依赖的类
package com.example
import java.util.UUID
import scaldi.Injector
import akka.actor.{Actor, ActorRef, PoisonPill}
import scaldi.akka.AkkaInjectable
import scala.math.BigDecimal.RoundingMode
class OrderProcessor(implicit inj: Injector) extends Actor with AkkaInjectable {
import Messages._
val priceCalculator = injectActorRef [PriceCalculator]
def receive = idle
val idle: Receive = {
case orderInfo @ ProcessOrder(user: User, itemId: Long, netAmount: Int) =>
println(s"Processing order for user $user.")
priceCalculator ! CalculatePrice(netAmount)
context become workingHard(orderInfo, sender)
}
def workingHard(orderInfo: ProcessOrder, reportTo: ActorRef): Receive = {
case CancelProcessing =>
reportTo ! OrderProcessingFailed("Canceled..")
self ! PoisonPill
case GrossPriceCalculated(_, grossPrice) =>
println("Processing order.....")
reportTo ! OrderProcessed(UUID.randomUUID().toString, grossPrice)
self ! PoisonPill
}
}
class PriceCalculator extends Actor {
import Messages._
def receive = {
case CalculatePrice(netAmount) =>
val grossCent = (netAmount * BigDecimal("1.19")).setScale(0, RoundingMode.HALF_UP).toIntExact
sender ! GrossPriceCalculated(netAmount, grossCent)
}
}
示例2: 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)
}
}
示例3: ControllerSpec
//设置package包名称以及导入依赖的类
package akka.remote.testconductor
import akka.testkit.AkkaSpec
import akka.actor.{ PoisonPill, Props, AddressFromURIString }
import akka.testkit.ImplicitSender
import akka.remote.testconductor.Controller.NodeInfo
import java.net.InetSocketAddress
import java.net.InetAddress
object ControllerSpec {
val config = """
akka.testconductor.barrier-timeout = 5s
akka.actor.provider = akka.remote.RemoteActorRefProvider
akka.actor.debug.fsm = on
akka.actor.debug.lifecycle = on
"""
}
class ControllerSpec extends AkkaSpec(ControllerSpec.config) with ImplicitSender {
val A = RoleName("a")
val B = RoleName("b")
"A Controller" must {
"publish its nodes" in {
val c = system.actorOf(Props(classOf[Controller], 1, new InetSocketAddress(InetAddress.getLocalHost, 0)))
c ! NodeInfo(A, AddressFromURIString("akka://sys"), testActor)
expectMsg(ToClient(Done))
c ! NodeInfo(B, AddressFromURIString("akka://sys"), testActor)
expectMsg(ToClient(Done))
c ! Controller.GetNodes
expectMsgType[Iterable[RoleName]].toSet should be(Set(A, B))
c ! PoisonPill // clean up so network connections don't accumulate during test run
}
}
}
示例4: Echoer
//设置package包名称以及导入依赖的类
import akka.actor.{PoisonPill, Props, ActorSystem, Actor}
class Echoer extends Actor {
def receive = {
case m:String =>
println(m)
}
}
object EchoApp extends App {
val system = ActorSystem("echosystem")
val echoer = system.actorOf(Props[Echoer], "echoer")
echoer ! "Hello!"
echoer ! PoisonPill
system.terminate
}
示例5: Init6
//设置package包名称以及导入依赖的类
package com.init6
import java.util.concurrent.TimeUnit
import akka.actor.{ActorRef, PoisonPill}
import com.init6.channels.ChannelsActor
import com.init6.connection.websocket.WebSocketConnectionHandler
import com.init6.connection.{ConnectionHandler, IpLimitActor}
import com.init6.db.{DAO, DAOActor}
import com.init6.servers.{ServerAnnouncementActor, ServerRegistry}
import com.init6.users.{RankingActor, TopCommandActor, UsersActor}
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.Random
object Init6 extends App with Init6Component {
DAO
ServerRegistry()
DAOActor()
IpLimitActor(Config().Accounts.connectionLimit)
UsersActor()
ChannelsActor()
TopCommandActor()
RankingActor()
ServerAnnouncementActor(args(0).toLong)
val random = new Random(System.nanoTime())
val delay =
if (random.nextInt(100) < Config().Server.reconThreshold) {
0
} else {
12
}
var connectionHandlers: Seq[ActorRef] = _
import system.dispatcher
system.scheduler.scheduleOnce(
Duration(delay, TimeUnit.SECONDS)
)({
connectionHandlers = Config().Server.ports
.map(port => {
ConnectionHandler(Config().Server.host, port)
}) :+
WebSocketConnectionHandler()
})
sys.addShutdownHook({
Option(connectionHandlers).foreach(_.foreach(_ ! PoisonPill))
implicit val timeout = Duration(10, TimeUnit.SECONDS)
Await.ready(system.terminate(), timeout)
DAO.close()
})
}
示例6: ListActor
//设置package包名称以及导入依赖的类
package actors
import akka.actor.{PoisonPill, Actor}
class ListActor extends Actor {
lazy val list: List[Int] = List(3,1,4,1,5,9,2,6,5,8,9,7,9,3,2,3,8)
// sends back an Either[Int, List] to the sender
def receive: Receive = {
case "sum" =>
// return sum of list
sender() ! Left(0)
self ! PoisonPill
case "median" =>
// return median of list
sender() ! Left(0)
self ! PoisonPill
case "average" =>
// return average of list
sender() ! Left(0)
self ! PoisonPill
case _ =>
sender() ! Right(getList)
self ! PoisonPill
}
def getList: List[Int] = {
list
}
}
示例7: ActorModule
//设置package包名称以及导入依赖的类
package module
import actors.{AkkaConfig, MainActor}
import akka.actor.{ActorRef, PoisonPill, Props, ActorSystem}
import akka.cluster.singleton.{ClusterSingletonManager, ClusterSingletonManagerSettings, ClusterSingletonProxy, ClusterSingletonProxySettings}
import scaldi.Module
import service.{SessionService, PaymentMethodService, AddressService}
class ActorModule extends Module {
bind[AddressService] toProvider new AddressService()
bind[PaymentMethodService] toProvider new PaymentMethodService()
bind[MainActor] to new MainActor(inject[PaymentMethodService], inject[AddressService])
bind[ActorSystem] to {
val actorSystem = ActorSystem("rest-akka-cluster", new AkkaConfig(None).config)
actorSystem.actorOf(
ClusterSingletonManager.props(
singletonProps = Props(inject[MainActor]),
terminationMessage = PoisonPill,
settings = ClusterSingletonManagerSettings(actorSystem).withSingletonName("MainActor")
), name = "singleton")
actorSystem
} destroyWith(_.terminate)
binding identifiedBy "MainActorProxy" to {
val system = inject[ActorSystem]
system.actorOf(
props = ClusterSingletonProxy.props(singletonManagerPath = "/user/singleton",
settings = ClusterSingletonProxySettings(system).withSingletonName("MainActor")
), name = "main-proxy")
}
bind[SessionService] toProvider new SessionService(inject[ActorRef]("MainActorProxy"))
}
示例8: Main
//设置package包名称以及导入依赖的类
package com.bau5.sitetracker.server
import akka.actor.PoisonPill
import akka.util.Timeout
import com.bau5.sitetracker.common.BaseProvider
import com.bau5.sitetracker.common.Events.{Message, MessageAll, SaveRequest}
import scala.concurrent.duration._
import scala.io.StdIn
object Main extends BaseProvider("ServerSystem", "") {
override implicit val timeout: Timeout = Timeout(5 seconds)
val messageAll = "message-all (.+)".r
def main(args: Array[String]) {
val serverActor = newActor[ServerActor]("server")
serverActor ! LoadSavedData
while (true) StdIn.readLine("> ") match {
case "save" =>
serverActor ! SaveRequest
case "quit" =>
serverActor ! SaveRequest
serverActor ! PoisonPill
sys.exit(0)
case messageAll(msg) =>
serverActor ! MessageAll(Message(msg))
case _ =>
println("Unrecognized input.")
}
}
}
示例9: StatsSampleOneMaster
//设置package包名称以及导入依赖的类
package sample.cluster.stats
import com.typesafe.config.ConfigFactory
import akka.actor.ActorSystem
import akka.actor.PoisonPill
import akka.actor.Props
import akka.cluster.singleton.ClusterSingletonManager
import akka.cluster.singleton.ClusterSingletonManagerSettings
import akka.cluster.singleton.ClusterSingletonProxy
import akka.cluster.singleton.ClusterSingletonProxySettings
object StatsSampleOneMaster {
def main(args: Array[String]): Unit = {
if (args.isEmpty) {
startup(Seq("2551", "2552", "0"))
StatsSampleOneMasterClient.main(Array.empty)
} else {
startup(args)
}
}
def startup(ports: Seq[String]): Unit = {
ports foreach { port =>
// Override the configuration of the port when specified as program argument
val config =
ConfigFactory.parseString(s"akka.remote.netty.tcp.port=" + port).withFallback(
ConfigFactory.parseString("akka.cluster.roles = [compute]")).
withFallback(ConfigFactory.load("stats2"))
val system = ActorSystem("ClusterSystem", config)
system.actorOf(ClusterSingletonManager.props(
singletonProps = Props[StatsService],
terminationMessage = PoisonPill,
settings = ClusterSingletonManagerSettings(system).withRole("compute")),
name = "statsService")
system.actorOf(ClusterSingletonProxy.props(singletonManagerPath = "/user/statsService",
settings = ClusterSingletonProxySettings(system).withRole("compute")),
name = "statsServiceProxy")
}
}
}
object StatsSampleOneMasterClient {
def main(args: Array[String]): Unit = {
// note that client is not a compute node, role not defined
val system = ActorSystem("ClusterSystem")
system.actorOf(Props(classOf[StatsSampleClient], "/user/statsServiceProxy"), "client")
}
}
示例10: TicketSeller
//设置package包名称以及导入依赖的类
package akka_in_action
import akka.actor.{Props, PoisonPill, Actor}
class TicketSeller extends Actor {
import TicketProtocol._
var tickets = Vector[Ticket]()
def receive = {
case GetEvents => sender ! tickets.size
case Tickets(newTickets) =>
tickets = tickets ++ newTickets
case BuyTicket =>
if (tickets.isEmpty) {
sender ! SoldOut
self ! PoisonPill
}
tickets.headOption.foreach { ticket =>
tickets = tickets.tail
sender ! ticket
}
case Event(name, nrOrTickets) =>
if (context.child(name).isEmpty) {
val ticketSeller = context.actorOf(Props[TicketSeller], name)
val tickets = Tickets((1 to nrOrTickets).map{
nr => Ticket(name, nr)
}.toList)
ticketSeller ! tickets
}
sender ! EventCreated
}
}
示例11: ActorRefEx
//设置package包名称以及导入依赖的类
package com.udemy.akka.actorpath
import akka.actor.{ActorRef, ActorSelection, ActorSystem, PoisonPill, Props}
object ActorRefEx extends App{
val system=ActorSystem("PathSystem")
private val counter1: ActorRef = system.actorOf(Props[Counter],"counter")
println(s"Actor reference for counter $counter1")
private val counterSelection: ActorSelection = system.actorSelection("counter")
println(s"Actor selection for counter $counterSelection")
counter1 ! PoisonPill
Thread.sleep(100)
private val counter2: ActorRef = system.actorOf(Props[Counter],"counter")
println(s"Actor reference for counter $counter2")
private val counterSelection2: ActorSelection = system.actorSelection("counter")
println(s"Actor selection for counter $counterSelection2")
system.terminate()
}
示例12: draw
//设置package包名称以及导入依赖的类
package com.github.kelebra.akka.js.snake
import akka.actor.{Actor, ActorLogging, PoisonPill}
import org.scalajs.dom
import org.scalajs.dom.html
trait Drawing extends Actor with ActorLogging {
def draw(block: Block): Unit
def erase(block: Block): Unit
}
case class CanvasDrawing(canvas: html.Canvas) extends Drawing {
private val ctx = canvas.getContext("2d").asInstanceOf[dom.CanvasRenderingContext2D]
def draw(block: Block): Unit = ctx.fillRect(block.x, block.y, block.radius, block.radius)
def erase(block: Block): Unit = ctx.clearRect(block.x, block.y, block.radius, block.radius)
def canDraw(block: Block): Boolean = {
val radius = block.radius
(block.x + radius) < canvas.width &&
(block.x - radius) > 0 &&
(block.y + radius) < canvas.height &&
(block.y - radius) > 0
}
def receive: Receive = {
case Draw(block) if canDraw(block) => draw(block)
case Erase(block) => erase(block)
case _ =>
sender() ! PoisonPill
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.font = "20px Georgia"
ctx.fillText("You lost!", canvas.width / 2, canvas.height / 2)
}
}
示例13: PingActor
//设置package包名称以及导入依赖的类
package com.example
import akka.actor.{Actor, ActorLogging, PoisonPill, Props}
import cakesolutions.kafka.akka.KafkaConsumerActor.Confirm
import com.typesafe.config.Config
class PingActor(val config: Config) extends Actor
with ActorLogging with PingPongConsumer with PingPongProducer{
import PingActor._
import PingPongProtocol._
var counter = 0
override def preStart() = {
super.preStart()
subscribe(topics)
}
def receive = playingPingPong
def playingPingPong: Receive = {
case msgExtractor(consumerRecords) =>
consumerRecords.pairs.foreach {
case (None, pongMessage) =>
log.error(s"Received unkeyed message: $pongMessage")
case (Some(id), pongMessage) =>
println(pongMessage.text)
kafkaConsumerActor ! Confirm(consumerRecords.offsets)
log.info(s"In PingActor - id:$id, msg: $pongMessage, counter:$counter, offsets ${consumerRecords.offsets}")
counter += 1
if (counter >= 3) {
log.info(s"${self.path.name} is ending the game")
submitMsg(PongActor.topics, PingPongMessage("GameOver"))
// DO NOT do this in production, this is just to make sure that our kafkaConsumerActor is not terminated before placing the game over message
Thread.sleep(1000)
self ! PoisonPill
} else {
submitMsg(PongActor.topics, PingPongMessage("PONG"))
}
}
case unknown =>
log.error(s"got Unknown message: $unknown")
}
}
object PingActor {
def props(config: Config) = Props( new PingActor(config))
val topics = List("ping")
}
示例14: PongActor
//设置package包名称以及导入依赖的类
package com.example
import akka.actor.{Actor, ActorLogging, PoisonPill, Props}
import cakesolutions.kafka.akka.KafkaConsumerActor.Confirm
import com.typesafe.config.Config
class PongActor(val config: Config) extends Actor
with ActorLogging with PingPongConsumer with PingPongProducer{
import PingPongProtocol._
import PongActor._
override def preStart(): Unit = {
super.preStart()
subscribe(topics)
}
def receive = {
case Start =>
log.info("In PongActor - received start message - let the games begin")
submitMsg(PingActor.topics,PingPongMessage("ping"))
context.become(playingPingPong)
}
def playingPingPong: Receive ={
case msgExtractor(consumerRecords) =>
consumerRecords.pairs.foreach {
case (_, PingPongMessage("GameOver")) =>
kafkaConsumerActor ! Confirm(consumerRecords.offsets)
log.info(s"Bye Bye ${self.path.name}")
self ! PoisonPill
case (None, msg) =>
log.error(s"Received unkeyed submit sample command: $msg")
case (Some(id), pongMessage) =>
kafkaConsumerActor ! Confirm(consumerRecords.offsets)
log.info(s"In PongActor - id:$id, msg: $pongMessage, offsets ${consumerRecords.offsets}")
println(pongMessage.text)
submitMsg(PingActor.topics, PingPongMessage("ping"))
}
case unknown =>
log.error(s"PongActor got Unknown message: $unknown")
}
}
object PongActor {
def props(config: Config) = Props(new PongActor(config))
val topics = List("pong")
case object Start
}
示例15: CaptureEvents
//设置package包名称以及导入依赖的类
package mesosphere.marathon.test
import akka.actor.ActorDSL._
import akka.actor.{ ActorSystem, PoisonPill, Terminated }
import akka.event.EventStream
import akka.testkit.TestProbe
import mesosphere.marathon.core.event.MarathonEvent
import scala.collection.immutable.Seq
import scala.concurrent.Await
import scala.concurrent.duration.Duration
class CaptureEvents(eventStream: EventStream) {
def forBlock(block: => Unit): Seq[MarathonEvent] = {
implicit val actorSystem = ActorSystem("captureEvents")
// yes, this is ugly. Since we only access it in the actor until it terminates, we do have
// the correct thread sync boundaries in place.
var capture = Vector.empty[MarathonEvent]
val captureEventsActor = actor {
new Act {
become {
case captureMe: MarathonEvent => capture :+= captureMe
}
}
}
eventStream.subscribe(captureEventsActor, classOf[MarathonEvent])
eventStream.subscribe(captureEventsActor, classOf[String])
try {
block
} finally {
eventStream.unsubscribe(captureEventsActor)
captureEventsActor ! PoisonPill
val probe = TestProbe()
probe.watch(captureEventsActor)
probe.expectMsgClass(classOf[Terminated])
Await.result(actorSystem.terminate(), Duration.Inf)
}
capture
}
}