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


Scala ActorLogging类代码示例

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


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

示例1: RoutesActor

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


import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.ActorLogging
import akka.actor.Props

import play.api.libs.json.Json.toJson

import bmmessages._
import akka.actor.Terminated

class RoutesActor extends Actor with ActorLogging {
	var originSender : ActorRef = null
	var next : ActorRef = null
	def receive = {
		case excute(msr)  => {
		    implicit val cm = msr.cm
		    
			originSender = sender
			msr.lst match {
				case Nil => originSender ! toJson("error")
				case head :: tail => {
					head match {
						case p : ParallelMessage => {
							next = context.actorOf(ScatterGatherActor.prop(self, MessageRoutes(tail, msr.rst)), "gate")
							next ! head
						}
						case c : CommonMessage => {
							next = context.actorOf(PipeFilterActor.prop(self, MessageRoutes(tail, msr.rst)), "gate")
							next ! head
						}
					}
					
					context.watch(next)
				}
			}
		}
		case result(rst) => {
			originSender ! rst
			cancelActor
		}
		case error(err) => {
			originSender ! err
			cancelActor
		}
		case bmmessages.timeout() => {
			originSender ! toJson("timeout")
			cancelActor
		}
		case Terminated(actorRef) => println("Actor {} terminated", actorRef)
		case _ => Unit
 	}
	
	def cancelActor = {
		context.stop(self)
	}
} 
开发者ID:AlfredYang1986,项目名称:arch-started,代码行数:60,代码来源:RoutesActor.scala

示例2: UserActor

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

import akka.actor.Actor
import akka.actor.ActorLogging
import akka.event.LoggingReceive
import play.api.libs.json.JsValue
import play.api.libs.json.Json
import akka.actor.ActorRef
import akka.actor.Props
import scala.xml.Utility


class UserActor(uid: String, board: ActorRef, out: ActorRef) extends Actor with ActorLogging {


  override def preStart() = {
    BoardActor() ! Subscribe
  }

  def receive = LoggingReceive {
    case Message(muid, s) if sender == board => {
      val js = Json.obj("type" -> "message", "uid" -> muid, "msg" -> s)
      out ! js
    }
    case js: JsValue => (js \ "msg").validate[String] map { Utility.escape(_) }  map { board ! Message(uid, _ ) }
    case other => log.error("unhandled: " + other)
  }
}

object UserActor {
  def props(uid: String)(out: ActorRef) = Props(new UserActor(uid, BoardActor(), out))
} 
开发者ID:OCervantes,项目名称:websocket-play,代码行数:33,代码来源:UserActor.scala

示例3: BoardActor

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

import akka.actor.Actor
import akka.actor.ActorLogging
import akka.event.LoggingReceive
import akka.actor.ActorRef
import akka.actor.Terminated
import play.libs.Akka
import akka.actor.Props

class BoardActor extends Actor with ActorLogging {
  var users = Set[ActorRef]()

  def receive = LoggingReceive {
    case m:Message => users map { _ ! m}
    case Subscribe => {
      users += sender
      context watch sender
    }
    case Terminated(user) => users -= user
  }
}

object BoardActor {
  lazy val board = Akka.system().actorOf(Props[BoardActor])
  def apply() = board
}

case class Message(uuid: String, s: String)
object Subscribe 
开发者ID:OCervantes,项目名称:websocket-play,代码行数:31,代码来源:BoardActor.scala

示例4: GreeterMessages

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

import akka.actor.Actor
import akka.actor.ActorLogging

// Note: Usually the message object (GreeterMessages) and the actor class (GreeterActor) will be called the same thing (eg. Greeter)
object GreeterMessages {
  case object Greet
  case object Done
}

class GreeterActor extends Actor with ActorLogging {

  def receive = {
    case GreeterMessages.Greet => {
      var greetMsg = "Hello World!"

      println(greetMsg)
      log.info(greetMsg)

      sender() ! GreeterMessages.Done // Send the 'Done' message back to the sender
    }
  }

} 
开发者ID:otobrglez,项目名称:proto,代码行数:26,代码来源:GreeterActor.scala

示例5: MainAppActor

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

import akka.actor.{Actor, ActorLogging, ActorRef, ActorSystem}
import com.github.unknownnpc.remotedebugtool.message._

import scala.concurrent.ExecutionContext

class MainAppActor()(implicit actorSystem: ActorSystem) extends Actor with ActorLogging {

  private implicit val dispatcher: ExecutionContext = actorSystem.dispatcher

  private var jdiVmServiceActor: ActorRef = _
  private var reportServiceActor: ActorRef = _

  override def preStart(): Unit = {
    log.info("Main app actor starts")
    reportServiceActor = createReportServiceActor()
    jdiVmServiceActor = createJdiVmServiceActor()
  }

  override def postStop() {
    log.info("Main app actor stops")
  }

  override def receive: Receive = {

    case MainAppActorStart =>
      startServices()

    case MainAppActorStop =>
      stopServices()
      context.stop(self)
      context.system.terminate()

  }

  private def startServices() = {
    jdiVmServiceActor ! JdiVmServiceStart
  }

  private def stopServices() = {
    log.info("Received command to stop all services")
    jdiVmServiceActor ! JdiVmServiceStop
    reportServiceActor ! ReportServiceStop
  }

  private def createJdiVmServiceActor() = {
    context.actorOf(JdiVmServiceActor.props(reportServiceActor), "jdi-vm-service")
  }

  private def createReportServiceActor() = {
    context.actorOf(ReportServiceActor.props(self), "report-service")
  }

} 
开发者ID:UnknownNPC,项目名称:remote-debug-tool,代码行数:56,代码来源:MainAppActor.scala

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

示例7: SimpleClusterListener

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

import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import akka.actor.ActorLogging
import akka.actor.Actor

class SimpleClusterListener extends Actor with ActorLogging {

  val cluster = Cluster(context.system)

  // subscribe to cluster changes, re-subscribe when restart 
  override def preStart(): Unit = {
    //#subscribe
    cluster.subscribe(self, initialStateMode = InitialStateAsEvents,
      classOf[MemberEvent], classOf[UnreachableMember])
    //#subscribe
  }
  override def postStop(): Unit = cluster.unsubscribe(self)

  def receive = {
    case MemberUp(member) =>
      log.info("Member is Up: {}", member.address)
    case UnreachableMember(member) =>
      log.info("Member detected as unreachable: {}", member)
    case MemberRemoved(member, previousStatus) =>
      log.info("Member is Removed: {} after {}",
        member.address, previousStatus)
    case _: MemberEvent => // ignore
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:32,代码来源:SimpleClusterListener.scala

示例8: SimpleClusterListener2

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

import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import akka.actor.ActorLogging
import akka.actor.Actor

class SimpleClusterListener2 extends Actor with ActorLogging {

  val cluster = Cluster(context.system)

  // subscribe to cluster changes, re-subscribe when restart 
  override def preStart(): Unit = {
    //#subscribe
    cluster.subscribe(self, classOf[MemberEvent], classOf[UnreachableMember])
    //#subscribe
  }
  override def postStop(): Unit = cluster.unsubscribe(self)

  def receive = {
    case state: CurrentClusterState =>
      log.info("Current members: {}", state.members.mkString(", "))
    case MemberUp(member) =>
      log.info("Member is Up: {}", member.address)
    case UnreachableMember(member) =>
      log.info("Member detected as unreachable: {}", member)
    case MemberRemoved(member, previousStatus) =>
      log.info("Member is Removed: {} after {}",
        member.address, previousStatus)
    case _: MemberEvent => // ignore
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:33,代码来源:SimpleClusterListener2.scala

示例9: Main2

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

import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor.ActorRef
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.Terminated

object Main2 {

  def main(args: Array[String]): Unit = {
    val system = ActorSystem("Hello")
    val a = system.actorOf(Props[HelloWorld], "helloWorld")
    system.actorOf(Props(classOf[Terminator], a), "terminator")
  }

  class Terminator(ref: ActorRef) extends Actor with ActorLogging {
    context watch ref
    def receive = {
      case Terminated(_) =>
        log.info("{} has terminated, shutting down system", ref.path)
        context.system.shutdown()
    }
  }

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

示例10: main

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

import akka.actor.ActorSystem
import akka.actor.ExtendedActorSystem
import akka.actor.Actor
import akka.actor.Terminated
import akka.actor.ActorLogging
import akka.actor.Props
import akka.actor.ActorRef
import scala.util.control.NonFatal


  def main(args: Array[String]): Unit = {
    if (args.length != 1) {
      println("you need to provide exactly one argument: the class of the application supervisor actor")
    } else {
      val system = ActorSystem("Main")
      try {
        val appClass = system.asInstanceOf[ExtendedActorSystem].dynamicAccess.getClassFor[Actor](args(0)).get
        val app = system.actorOf(Props(appClass), "app")
        val terminator = system.actorOf(Props(classOf[Terminator], app), "app-terminator")
      } catch {
        case NonFatal(e) ? system.shutdown(); throw e
      }
    }
  }

  class Terminator(app: ActorRef) extends Actor with ActorLogging {
    context watch app
    def receive = {
      case Terminated(_) ?
        log.info("application supervisor has terminated, shutting down")
        context.system.shutdown()
    }
  }

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

示例11: CustomOneForOneUser

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

import akka.actor.SupervisorStrategy.{Restart, Stop}
import akka.actor.{Actor, ActorLogging, ActorRef, OneForOneStrategy}


class CustomOneForOneUser extends Actor with ActorLogging {

  // Map that keeps track of how often a given child has been restarted
  var restarts = Map.empty[ActorRef, Int].withDefaultValue(0)

  // Using the default parameters for a SupervisorStrategy mean "arbitarily
  // often over forever"
  override val supervisorStrategy = OneForOneStrategy() {

    case _: ArithmeticException =>

      restarts(sender) match {
        case tooManyRestarts if tooManyRestarts > 15 =>
          restarts -= sender
          Stop
        case n =>
          restarts = restarts.updated(sender, n+1)
          Restart
      }
  }

  override def receive: Receive = ???
} 
开发者ID:dkmn,项目名称:week-3-lecture-examples,代码行数:30,代码来源:CustomOneForOneUser.scala

示例12: LongConsumer

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

import akka.actor.{Actor, ActorLogging}
import sample.kamon.KafkaActorConsumer.Consume

class LongConsumer extends Actor with ActorLogging {

  val telemetryDumperSupervisor = context.actorOf(
    TelemetryDumperSupervisor.props(),
    "telemetry-dumper-supervisor"
  )

  lazy val topicStream: Iterable[Int] = Stream.from(1)

  override def preStart(): Unit = {
    log.info("######## LongConsumer preStart!!!")
    self ! Consume
  }

  def receive: Receive = {
    case Consume =>
      log.info("######## LongConsumer Consume!!!")
      topicStream foreach { kafkaMessage =>
        consume(kafkaMessage)
      }
  }

  def consume(kafkaMessage: Int): Unit = {
    telemetryDumperSupervisor ! kafkaMessage
  }
}

object KafkaActorConsumer {
  object Consume
  object Start
} 
开发者ID:frossi85,项目名称:akka-kamon-sample,代码行数:37,代码来源:LongConsumer.scala

示例13: TelemetryDumperSupervisor

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

import akka.actor.SupervisorStrategy.Restart
import akka.actor.{Actor, ActorLogging, OneForOneStrategy, Props}
import sample.kamon.TelemetryDumperSupervisor.Saved

import scala.util.Random

class TelemetryDumperSupervisor extends Actor with ActorLogging {

  log.info("TelemetryDumperSupervisor started!")

  override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) {
    case e: Exception =>
      log.error(e, "There was an error when trying to save telemetry data, restarting.")
      Restart
  }

  def receive: Receive = {
    case telemetry: Int =>
      Thread.sleep(40 * Random.nextInt(10))
      context.actorOf(TelemetryDumper.props(new SimpleBackoffStrategy, telemetry))
    case Saved(telemetry) =>
    //Make some post process
  }
}

object TelemetryDumperSupervisor {
  def props(): Props = Props(classOf[TelemetryDumperSupervisor])

  case class Saved(telemetry: Int)
} 
开发者ID:frossi85,项目名称:akka-kamon-sample,代码行数:33,代码来源:TelemetryDumperSupervisor.scala

示例14: commandHandler

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

import akka.actor.ActorLogging
import akka.persistence.PersistentActor
import lib.models.PayLoad

import scala.concurrent.duration._


trait Monitor extends PersistentActor with ActorLogging {
  context.setReceiveTimeout(120.seconds)

  final val persistenceId: String = self.path.name
  def commandHandler: Receive
  def recoverHandler:Receive
  final def receiveRecover: Receive = defaultRecoverHandler orElse recoverHandler
  final def receiveCommand: Receive = defaultCommandHandler orElse commandHandler
  final def defaultCommandHandler: Receive = {
    case payLoad: PayLoad => log.warning(s"No command handler for Payload [$payLoad] for the monitor $persistenceId")
  }
  final def defaultRecoverHandler: Receive = {
    case msg => log.warning(s"No recover handler for msg [$msg] for the monitor $persistenceId")
  }
} 
开发者ID:sharma-rohit,项目名称:mormont,代码行数:25,代码来源:Monitor.scala

示例15: ChunkedHermesGameFileEntries

//设置package包名称以及导入依赖的类
package proton.game.hermes

import java.util.UUID

import akka.actor.ActorLogging
import akka.event.LoggingReceive
import akka.persistence.PersistentActor

import scala.collection.mutable.ListBuffer

object ChunkedHermesGameFileEntries {
  trait EntriesMessage
  case class AppendEntries(entries: Seq[HermesGameFileEntry]) extends EntriesMessage
  case class GetEntries() extends EntriesMessage

  trait EntriesEvent
  case class EntriesAppended(entries: Seq[HermesGameFileEntry]) extends EntriesEvent

  trait EntriesResult
  case class EntriesAppendedResult(id: UUID, count: Int) extends EntriesResult
  case class GetEntriesResult(id: UUID, entries: Seq[HermesGameFileEntry]) extends EntriesResult

  val gameFileEntriesRegionName = "hermesGameFileEntries"
}

class ChunkedHermesGameFileEntries(moduleSettings: HermesGameTickerModuleSettings) extends PersistentActor with ActorLogging {
  import context._
  import ChunkedHermesGameFileEntries._

  private val _id: UUID = UUID.fromString(self.path.name)
  private val _entries = new ListBuffer[HermesGameFileEntry]()

  setReceiveTimeout(moduleSettings.chunkedTimeout)

  override def receiveRecover: Receive = {
    case event: EntriesEvent => updateState(event)
  }

  def updateState(e: EntriesEvent) = e match {
    case EntriesAppended(entries) => _entries ++= entries
  }

  override def receiveCommand: Receive = LoggingReceive {
    case AppendEntries(entries) =>
      if (entries.nonEmpty) {
        persist(EntriesAppended(entries))(e => {
          updateState(e)
          sender ! EntriesAppendedResult(_id, entries.size)
        })
      } else {
        sender ! EntriesAppendedResult(_id, 0)
      }
    case GetEntries() => sender ! GetEntriesResult(_id, _entries)
  }

  override def persistenceId: String = "hermes-game-file-entries-" + _id.toString
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:58,代码来源:ChunkedHermesGameFileEntries.scala


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