本文整理汇总了Scala中akka.event.LoggingReceive类的典型用法代码示例。如果您正苦于以下问题:Scala LoggingReceive类的具体用法?Scala LoggingReceive怎么用?Scala LoggingReceive使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了LoggingReceive类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: AuctionSearch
//设置package包名称以及导入依赖的类
package reactive4.homework
import akka.actor.{Actor, ActorRef}
import akka.event.LoggingReceive
import reactive4.homework.AuctionSearch.{AddAuction, SearchAuction, SearchResult}
class AuctionSearch extends Actor {
var map:Map[String, ActorRef] = Map()
override def receive: Receive = LoggingReceive {
case msg: AddAuction =>
map = map + ((msg.title, msg.auction))
case msg: SearchAuction =>
val list: List[ActorRef] = map.filterKeys(_.contains(msg.query)).values.toList
sender() ! SearchResult(msg.query, list)
}
}
object AuctionSearch {
case class AddAuction(title: String, auction:ActorRef)
case class SearchAuction(query: String)
case class SearchResult(query: String, auctions: List[ActorRef])
}
示例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))
}
示例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
示例4: WireTransfer
//设置package包名称以及导入依赖的类
package bank
import akka.actor.{Props, Actor, ActorRef}
import akka.event.LoggingReceive
object WireTransfer {
val props = Props[WireTransfer]
case class Transfer(from: ActorRef, to: ActorRef, amount: BigInt)
case object Done
case object Failed
}
class WireTransfer extends Actor {
import WireTransfer._
def awaitFrom(to: ActorRef, amount: BigInt, consumer: ActorRef): Receive = LoggingReceive {
case BankAccount.Done =>
to ! BankAccount.Deposit(amount)
context.become(awaitTo(consumer)) //
case BankAccount.Failed =>
consumer ! Failed
}
def awaitTo(consumer: ActorRef): Receive = LoggingReceive {
case BankAccount.Done =>
consumer ! Done
context.stop(self)
case BankAccount.Failed =>
consumer ! Failed
context.stop(self)
}
override def receive: Receive = LoggingReceive {
case Transfer(from, to, amount) =>
from ! BankAccount.Withdraw(amount)
context.become(awaitFrom(to, amount, sender))
}
}
示例5: 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
}
示例6: MessageMaintainer
//设置package包名称以及导入依赖的类
package workers
import akka.actor.{ Actor, ActorLogging, ActorRef, Props }
import akka.event.LoggingReceive
import domain.common.MessageToken
import domain.news.NewsMessage
import domain.news.{ ContentOperation, MasterOperation, Operation }
import services.ContentRegisterService
import tasks.{ ContentRegisterTask, MasterRegisterTask }
import workers.MessageMaintainer.{ Maintain, MaintainFailed, MaintainSucceeded }
class MessageMaintainer(
deleter: ActorRef,
contentRegisterService: ContentRegisterService
) extends Actor with ActorLogging {
val masterRegisterTask: ActorRef = context.actorOf(Props(
classOf[MasterRegisterTask], self
), "MasterRegisterTask")
val contentRegisterTask: ActorRef = context.actorOf(Props(
classOf[ContentRegisterTask], self, contentRegisterService
), "ContentRegisterTask")
override def receive: Receive = LoggingReceive {
case [email protected](message, messageToken) =>
log.info(s"News job start:${ message.operation }, $messageToken")
message.operation match {
case MasterOperation => masterRegisterTask ! m
case ContentOperation => contentRegisterTask ! m
}
case MaintainSucceeded(operation, messageToken) =>
log.info(s"News Job succeeded:$operation, $messageToken")
deleter ! MessageDeleter.Delete(messageToken)
case MaintainFailed(operation, messageToken, e) =>
log.warning(s"News Job succeeded:$operation, $messageToken", e)
deleter ! MessageDeleter.Delete(messageToken)
}
}
object MessageMaintainer {
case class Maintain(
message: NewsMessage,
messageToken: MessageToken
)
case class MaintainSucceeded(
operation: Operation,
messageToken: MessageToken
)
case class MaintainFailed(
operation: Operation,
messageToken: MessageToken,
e: Throwable
)
}
示例7: UserSocket
//设置package包名称以及导入依赖的类
package actors
import actors.UserSocket.{ChatMessage, Message}
import actors.UserSocket.Message.messageReads
import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.{Publish, Subscribe}
import akka.event.LoggingReceive
import play.api.libs.json.{Writes, JsValue, Json}
import play.twirl.api.HtmlFormat
import scala.xml.Utility
object UserSocket {
def props(user: String)(out: ActorRef) = Props(new UserSocket(user, out))
case class Message(msg: String)
object Message {
implicit val messageReads = Json.reads[Message]
}
case class ChatMessage(user: String, text: String)
object ChatMessage {
implicit val chatMessageWrites = new Writes[ChatMessage] {
def writes(chatMessage: ChatMessage): JsValue = {
Json.obj(
"type" -> "message",
"user" -> chatMessage.user,
"text" -> multiLine(chatMessage.text)
)
}
}
private def multiLine(text: String) = {
HtmlFormat.raw(text).body.replace("\n", "<br/>")
}
}
}
class UserSocket(uid: String, out: ActorRef) extends Actor with ActorLogging {
val topic = "chat"
val mediator = DistributedPubSub(context.system).mediator
mediator ! Subscribe(topic, self)
def receive = LoggingReceive {
case js: JsValue =>
js.validate[Message](messageReads)
.map(message => Utility.escape(message.msg))
.foreach { msg => mediator ! Publish(topic, ChatMessage(uid, msg))}
case c:ChatMessage => out ! Json.toJson(c)
}
}
示例8: SchedulerActor
//设置package包名称以及导入依赖的类
package mesosphere.mesos.simulation
import akka.actor.{ Actor, Stash }
import akka.event.LoggingReceive
import mesosphere.marathon.stream._
import org.apache.mesos.Protos.{ FrameworkID, MasterInfo, Offer, TaskStatus }
import org.apache.mesos.{ Scheduler, SchedulerDriver }
import org.slf4j.LoggerFactory
import scala.collection.immutable.Seq
object SchedulerActor {
private val log = LoggerFactory.getLogger(getClass)
case class Registered(
frameworkId: FrameworkID,
master: MasterInfo)
case class ResourceOffers(offers: Seq[Offer])
}
class SchedulerActor(scheduler: Scheduler) extends Actor with Stash {
import SchedulerActor._
var driverOpt: Option[SchedulerDriver] = None
def receive: Receive = waitForDriver
def waitForDriver: Receive = LoggingReceive.withLabel("waitForDriver") {
case driver: SchedulerDriver =>
log.info("received driver")
driverOpt = Some(driver)
context.become(handleCmds(driver))
unstashAll()
case _ => stash()
}
def handleCmds(driver: SchedulerDriver): Receive = LoggingReceive.withLabel("handleCmds") {
case Registered(frameworkId, masterInfo) =>
scheduler.registered(driver, frameworkId, masterInfo)
case ResourceOffers(offers) =>
scheduler.resourceOffers(driver, offers)
case status: TaskStatus =>
scheduler.statusUpdate(driver, status)
}
override def postStop(): Unit = {
driverOpt.foreach { driver => scheduler.disconnected(driver) }
}
}
示例9: ProbeActor
//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.leadership.impl
import akka.actor.{ ActorRef, Props, Actor }
import akka.event.LoggingReceive
import akka.testkit.TestProbe
object ProbeActor {
def props(testProbe: TestProbe): Props = Props(new ProbeActor(testProbe))
case class PreStart(self: ActorRef)
case class PostStop(self: ActorRef)
}
class ProbeActor(testProbe: TestProbe) extends Actor {
override def preStart(): Unit = {
testProbe.ref ! ProbeActor.PreStart(self)
}
override def postStop(): Unit = {
testProbe.ref ! ProbeActor.PostStop(self)
}
override def receive: Receive = LoggingReceive {
case any: Any =>
testProbe.ref.forward(any)
}
}
示例10: BankAccount
//设置package包名称以及导入依赖的类
package bank
import akka.actor.{Props, Actor}
import akka.event.LoggingReceive
object BankAccount {
val props = Props[BankAccount]
case class Deposit(amount: BigInt) {
require(amount > 0)
}
case class Withdraw(amount: BigInt) {
require(amount > 0)
}
case object Done
case object Failed
}
class BankAccount extends Actor {
import BankAccount._
var balance = BigInt(0)
override def receive: Receive = LoggingReceive {
case Deposit(amount) =>
balance += amount
sender ! Done
case Withdraw(amount) if amount <= balance =>
balance -= amount
sender ! Done
case _ => sender ! Failed
}
}
示例11: AuctionService
//设置package包名称以及导入依赖的类
package homework.withoutfsm
import akka.actor.{Actor, Props}
import akka.event.LoggingReceive
import homework.withoutfsm.Auction.{BidTimer, DeleteTimer}
class AuctionService extends Actor {
import AuctionService._
import scala.concurrent.duration._
override def receive: Receive = LoggingReceive {
case Init => {
val auctions = (1 to 10).map(i => this.context.system.actorOf(Props(Auction(i, BidTimer(20 seconds), DeleteTimer(10 seconds), BigDecimal(2)))))
val buyers = (1 to 3).map(i => this.context.system.actorOf(Props(Buyer(i, auctions))))
auctions.foreach(_ ! Auction.AuctionCreated)
buyers.foreach(_ ! Buyer.Init)
}
case Finish => context.system.terminate()
}
}
object AuctionService {
case object Init
case object Finish
}
示例12: 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(nick: String, userId: Int, board: ActorRef, out: ActorRef) extends Actor with ActorLogging {
override def preStart() = {
board ! Subscribe
import UserActor._
val js = Json.obj("type" -> "info", "img" -> userId % AvatarCount)
out ! js
}
def receive = LoggingReceive {
case Message(nickname, id, s) if sender == board =>
import UserActor._
if (nickname != nick) {
val js = Json.obj("type" -> "message", "nickname" -> nickname, "msg" -> s, "img" -> id % AvatarCount)
out ! js
}
case js: JsValue =>
(js \ "msg").validate[String] map {
Utility.escape
} foreach {
board ! Message(nick, userId, _)
}
case other =>
log.error("unhandled: " + other)
}
}
object UserActor {
val AvatarCount = 11
var userCount = 0
def props(nick: String)(out: ActorRef) = {
userCount += 1
Props(new UserActor(nick, userCount - 1, BoardActor(), out))
}
}
示例13: 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 foreach { user =>
user ! m
}
case Subscribe =>
users += sender
context watch sender
case Terminated(user) =>
users -= user
}
}
object BoardActor {
lazy val board: ActorRef = Akka.system().actorOf(Props[BoardActor])
def apply(): ActorRef = board
}
case class Message(nickname: String, userId: Int, msg: String)
object Subscribe
示例14: Api
//设置package包名称以及导入依赖的类
package api
import java.util.concurrent.TimeUnit
import akka.actor.{Actor, ActorLogging, Props}
import akka.event.LoggingReceive
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.stream.ActorMaterializer
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{Await, Future}
class Api() extends Actor with ActorLogging with ApiRoutes {
import context.dispatcher
implicit val system = context.system
implicit val materializer = ActorMaterializer()
log.info("Api up and running...")
val binding: Future[ServerBinding] = Http().bindAndHandle(routes, "0.0.0.0", 8080)
binding.onFailure {
case ex: Exception =>
log.error(ex, "Failed to bind to {}:{}!", "0.0.0.0", 8080)
}
override def postStop(): Unit = {
log.info("Stopping api...")
Await.result(binding.map(_.unbind()), FiniteDuration(30, TimeUnit.SECONDS))
}
def receive: Receive = LoggingReceive {
case a => log.warning("Unknown message")
}
}
object Api {
def name: String = "api"
def props(): Props = {
Props(
classOf[Api]
)
}
}
示例15: TransferMain
//设置package包名称以及导入依赖的类
package com.example.banking
import akka.actor.{Actor, Props}
import akka.event.LoggingReceive
class TransferMain extends Actor {
val accountA = context.actorOf(Props[BankAccount], "accountA")
val accountB = context.actorOf(Props[BankAccount], "accountB")
accountA ! BankAccount.Deposit(100)
def receive = LoggingReceive {
case BankAccount.Done => transfer(75)
}
def transfer(amount: BigInt): Unit = {
val transaction = context.actorOf(Props[WireTransfer], "transfer")
transaction ! WireTransfer.Transfer(accountA, accountB, amount)
context.become(LoggingReceive {
case WireTransfer.Done =>
println("success")
context.stop(self)
case WireTransfer.Failed =>
println("failed")
context.stop(self)
})
}
}