本文整理汇总了Scala中akka.actor.ActorSelection类的典型用法代码示例。如果您正苦于以下问题:Scala ActorSelection类的具体用法?Scala ActorSelection怎么用?Scala ActorSelection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ActorSelection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: PipeableFuture
//设置package包名称以及导入依赖的类
package akka.pattern
import language.implicitConversions
import scala.concurrent.{ Future, ExecutionContext }
import scala.util.{ Failure, Success }
import akka.actor.{ Status, ActorRef, Actor }
import akka.actor.ActorSelection
trait PipeToSupport {
final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) {
def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
future onComplete {
case Success(r) ? recipient ! r
case Failure(f) ? recipient ! Status.Failure(f)
}
future
}
def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = {
future onComplete {
case Success(r) ? recipient ! r
case Failure(f) ? recipient ! Status.Failure(f)
}
future
}
def to(recipient: ActorRef): PipeableFuture[T] = to(recipient, Actor.noSender)
def to(recipient: ActorRef, sender: ActorRef): PipeableFuture[T] = {
pipeTo(recipient)(sender)
this
}
def to(recipient: ActorSelection): PipeableFuture[T] = to(recipient, Actor.noSender)
def to(recipient: ActorSelection, sender: ActorRef): PipeableFuture[T] = {
pipeToSelection(recipient)(sender)
this
}
}
implicit def pipe[T](future: Future[T])(implicit executionContext: ExecutionContext): PipeableFuture[T] = new PipeableFuture(future)
}
示例2: 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()
}
示例3: Endpoint
//设置package包名称以及导入依赖的类
package soeendpoint
import akka.actor.{ Actor, ActorSelection }
import akka.pattern.{ ask }
import akka.util.{ Timeout }
import types.Messages._
object Endpoint {
}
class Endpoint extends Actor {
import Endpoint._
val requests = collection.mutable.Map[ Integer, List[ActorSelection] ]()
def receive = {
case AskFor(number) =>
val askerPath = sender().path.parent.parent./("user")./("Computer")
val askerSel = context.actorSelection(askerPath)
requests get number match {
case Some(list) =>
if(!list.contains(askerSel))
requests put (number, askerSel :: list)
case None =>
requests put (number, List(askerSel))
}
sender ! Registered
case AnswerFor(number, isPrime) =>
if(requests isDefinedAt number){
val askers = requests(number)
askers.map (ref => ref ! AnswerFor(number,isPrime))
}
requests remove number
}
}
示例4: RaftClient
//设置package包名称以及导入依赖的类
package ru.ifmo.ctddev.semenov.dkvs.client
import akka.actor.{Actor, ActorLogging, ActorSelection, ActorSystem, PoisonPill, Props}
import ru.ifmo.ctddev.semenov.dkvs.protocol.Command
import scala.util.{Failure, Success, Try}
class RaftClient(node: ActorSelection) extends Actor with ActorLogging {
import RaftClient._
override def receive: Receive = {
case ConsoleMessage(msg) => Try(Command(msg)) match {
case Success(command) => node ! command
case Failure(exception) => log.error(exception, "illegal command?..")
}
case RaftResponse(msg) =>
println(msg)
case Exit =>
self ! PoisonPill // graceful stop after processing remaining events
}
}
object RaftClient {
sealed trait Message
case class ConsoleMessage(msg: String) extends Message
case class RaftResponse(msg: String) extends Message
case object Exit extends Message
def props(node: ActorSelection) = Props(classOf[RaftClient], node)
def main(args: Array[String]) {
if (args.length != 3) {
println("Usage: RaftClient <host> <port> <id>")
} else {
val (host, port, id) = (args(0), args(1), args(2))
// TODO: check config
val system = ActorSystem("raft-client")
// it's irrational, that user should know (host,port,id) of node,
// it should connect to cluster, not to specific node. isn't it?
// TODO: add address to config or constant
// TODO: add option to connect to cluster
val clusterNode = system.actorSelection(s"akka.tcp://[email protected]$host:$port/user/dkvs-$id")
val client = system.actorOf(props(clusterNode), "raftClient")
for (line <- scala.io.Source.stdin.getLines()) {
client ! ConsoleMessage(line.trim)
}
client ! Exit
}
}
}
示例5: UserActor
//设置package包名称以及导入依赖的类
package actor
import akka.actor.{Actor, ActorRef, ActorSelection, Props}
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.{Subscribe, SubscribeAck}
import models.{ToPublish, _}
import play.api.libs.json.Json
import models.Formats._
import models.MsgTypes._
class UserActor(out: ActorRef) extends Actor {
val mediator: ActorRef = DistributedPubSub(context.system).mediator
mediator ! Subscribe("content", self)
val publisher: ActorSelection = context.system.actorSelection("/user/publisher")
val playlist: ActorSelection = context.system.actorSelection("/user/playlist")
playlist ! GetPlaylist
def receive = {
case SubscribeAck(Subscribe("content", None, `self`)) ? println("subscribing")
case msg: Payload if msg.event == PUBLISH =>
publisher ! ToPublish(msg)
case ToPublish(payload) =>
out ! payload
case msg: Payload if msg.event == PLAY || msg.event == STOP =>
playlist ! msg
case msg: Payload if msg.event == NEXT =>
playlist ! PlayNext
case msg: Payload if msg.event == ADD =>
playlist ! AddToPlaylist(msg.content.get)
case msg: Payload if msg.event == CLEAR =>
playlist ! ClearPlaylist
publisher ! ToPublish(msg)
case msg: Playlist =>
out ! Payload(PLAYLIST, Some(Json.toJson(msg).toString()))
case Payload(event, content) =>
out ! Payload("response", content)
}
}
object UserActor {
def props(out: ActorRef) = Props(new UserActor(out))
}
示例6: PlanNotifier
//设置package包名称以及导入依赖的类
package lila.plan
import akka.actor.ActorSelection
import scala.concurrent.duration._
import lila.hub.actorApi.timeline.{ Propagate }
import lila.notify.Notification.Notifies
import lila.notify.{ Notification, NotifyApi }
import lila.user.User
private[plan] final class PlanNotifier(
notifyApi: NotifyApi,
scheduler: lila.common.Scheduler,
timeline: ActorSelection
) {
def onStart(user: User) = fuccess {
scheduler.once(5 seconds) {
notifyApi.addNotification(Notification.make(
Notifies(user.id),
lila.notify.PlanStart(user.id)
))
}
val msg = Propagate(lila.hub.actorApi.timeline.PlanStart(user.id))
timeline ! (msg toFollowersOf user.id)
}
def onExpire(user: User) =
notifyApi.addNotification(Notification.make(
Notifies(user.id),
lila.notify.PlanExpire(user.id)
))
}
示例7: Messenger
//设置package包名称以及导入依赖的类
package lila.round
import akka.actor.ActorSelection
import actorApi._
import lila.chat.actorApi._
import lila.game.Game
import lila.i18n.I18nKey.{ Select => SelectI18nKey }
import lila.i18n.I18nKeys
final class Messenger(
val chat: ActorSelection,
i18nKeys: I18nKeys
) {
def system(game: Game, message: SelectI18nKey, args: Any*) {
val translated = message(i18nKeys).en(args: _*)
chat ! SystemTalk(watcherId(game.id), translated)
if (game.nonAi) chat ! SystemTalk(game.id, translated)
}
def systemForOwners(gameId: String, message: SelectI18nKey, args: Any*) {
val translated = message(i18nKeys).en(args: _*)
chat ! SystemTalk(gameId, translated)
}
def watcher(gameId: String, member: Member, text: String) =
member.userId foreach { userId =>
chat ! UserTalk(watcherId(gameId), userId, text)
}
private val whisperCommands = List("/whisper ", "/w ")
def owner(gameId: String, member: Member, text: String) = (member.userId match {
case Some(userId) =>
whisperCommands.collectFirst {
case command if text startsWith command =>
UserTalk(watcherId(gameId), userId, text drop command.size)
} orElse {
if (text startsWith "/") none // mistyped command?
else UserTalk(gameId, userId, text, public = false).some
}
case None =>
PlayerTalk(gameId, member.color.white, text).some
}) foreach chat.!
private def watcherId(gameId: String) = s"$gameId/w"
}
示例8: Notifier
//设置package包名称以及导入依赖的类
package lila.qa
import lila.hub.actorApi.timeline.{ Propagate, QaQuestion, QaAnswer, QaComment }
import lila.notify.Notification.Notifies
import lila.notify.{ Notification, NotifyApi }
import lila.user.User
import akka.actor.ActorSelection
private[qa] final class Notifier(
notifyApi: NotifyApi,
timeline: ActorSelection
) {
private[qa] def createQuestion(q: Question, u: User) {
val msg = Propagate(QaQuestion(u.id, q.id, q.title))
timeline ! (msg toFollowersOf u.id)
}
private[qa] def createAnswer(q: Question, a: Answer, u: User) {
val msg = Propagate(QaAnswer(u.id, q.id, q.title, a.id))
timeline ! (msg toFollowersOf u.id toUser q.userId exceptUser u.id)
if (u.id != q.userId) notifyAsker(q, a)
}
private[qa] def notifyAsker(q: Question, a: Answer) = {
import lila.notify.QaAnswer
import lila.common.String.shorten
val answererId = QaAnswer.AnswererId(a.userId)
val question = QaAnswer.Question(id = q.id, slug = q.slug, title = shorten(q.title, 80))
val answerId = QaAnswer.AnswerId(a.id)
val notificationContent = QaAnswer(answererId, question, answerId)
val notification = Notification.make(Notifies(q.userId), notificationContent)
notifyApi.addNotification(notification)
}
private[qa] def createQuestionComment(q: Question, c: Comment, u: User) {
val msg = Propagate(QaComment(u.id, q.id, q.title, c.id))
timeline ! (msg toFollowersOf u.id toUser q.userId exceptUser u.id)
}
private[qa] def createAnswerComment(q: Question, a: Answer, c: Comment, u: User) {
val msg = Propagate(QaComment(u.id, q.id, q.title, c.id))
timeline ! (msg toFollowersOf u.id toUser a.userId exceptUser u.id)
}
}
示例9: Analyser
//设置package包名称以及导入依赖的类
package lila.analyse
import akka.actor.ActorSelection
import chess.format.FEN
import lila.game.actorApi.InsertGame
import lila.game.GameRepo
import lila.hub.actorApi.map.Tell
final class Analyser(
indexer: ActorSelection,
requesterApi: RequesterApi,
roundSocket: ActorSelection,
bus: lila.common.Bus
) {
def get(id: String): Fu[Option[Analysis]] = AnalysisRepo byId id
def save(analysis: Analysis): Funit = GameRepo game analysis.id flatMap {
_ ?? { game =>
GameRepo.setAnalysed(game.id)
AnalysisRepo.save(analysis) >>
sendAnalysisProgress(analysis) >>- {
bus.publish(actorApi.AnalysisReady(game, analysis), 'analysisReady)
indexer ! InsertGame(game)
requesterApi save analysis
}
}
}
def progress(analysis: Analysis): Funit = sendAnalysisProgress(analysis)
private def sendAnalysisProgress(analysis: Analysis): Funit =
GameRepo gameWithInitialFen analysis.id map {
_ ?? {
case (game, initialFen) =>
roundSocket ! Tell(analysis.id, actorApi.AnalysisProgress(
analysis = analysis,
game = game,
variant = game.variant,
initialFen = initialFen | FEN(game.variant.initialFen)
))
}
}
}
示例10: Cli
//设置package包名称以及导入依赖的类
package lila.api
import akka.actor.ActorSelection
import lila.hub.actorApi.Deploy
private[api] final class Cli(bus: lila.common.Bus, renderer: ActorSelection) extends lila.common.Cli {
private val logger = lila.log("cli")
def apply(args: List[String]): Fu[String] = run(args).map(_ + "\n") ~ {
_.logFailure(logger, _ => args mkString " ") foreach { output =>
logger.info("%s\n%s".format(args mkString " ", output))
}
}
def process = {
case "deploy" :: "pre" :: Nil => remindDeploy(lila.hub.actorApi.DeployPre)
case "deploy" :: "post" :: Nil => remindDeploy(lila.hub.actorApi.DeployPost)
}
private def remindDeploy(event: Deploy): Fu[String] = {
bus.publish(event, 'deploy)
fuccess("Deploy in progress")
}
private def run(args: List[String]): Fu[String] = {
(processors lift args) | fufail("Unknown command: " + args.mkString(" "))
} recover {
case e: Exception => "ERROR " + e
}
private def processors =
lila.user.Env.current.cli.process orElse
lila.security.Env.current.cli.process orElse
lila.i18n.Env.current.cli.process orElse
lila.gameSearch.Env.current.cli.process orElse
lila.teamSearch.Env.current.cli.process orElse
lila.forumSearch.Env.current.cli.process orElse
lila.team.Env.current.cli.process orElse
lila.puzzle.Env.current.cli.process orElse
lila.tournament.Env.current.cli.process orElse
lila.explorer.Env.current.cli.process orElse
lila.fishnet.Env.current.cli.process orElse
lila.blog.Env.current.cli.process orElse
lila.study.Env.current.cli.process orElse
lila.studySearch.Env.current.cli.process orElse
lila.coach.Env.current.cli.process orElse
lila.evalCache.Env.current.cli.process orElse
process
}
示例11: PizzaClient
//设置package包名称以及导入依赖的类
package actors
import akka.actor.{Actor, ActorRef, ActorSelection, Address, Props, RelativeActorPath, RootActorPath}
import akka.actor.Actor.Receive
import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import messages._
import scala.concurrent.forkjoin.ThreadLocalRandom
object PizzaClient {
def props(servicePath: String)(user: ActorRef) = Props(classOf[PizzaClient], servicePath, user)
}
class PizzaClient(servicePath: String, user: ActorRef) extends Actor {
val cluster = Cluster(context.system)
var nodes = Set.empty[Address]
val servicePathElements = servicePath match {
case RelativeActorPath(elements) => elements
case _ => throw new IllegalArgumentException("servicePath [%s] is not a valid relative actor path" format servicePath)
}
override def preStart(): Unit = {
cluster.subscribe(self, initialStateMode = InitialStateAsEvents, classOf[MemberEvent], classOf[ReachabilityEvent])
}
override def postStop(): Unit = {
cluster.unsubscribe(self)
}
override def receive: Receive = {
case order: PizzaCustomerOrder => {
// find service actor
val service = findServiceActor()
service ! order
}
case stop: PizzaCustomerStop => {
// find service actor
val service = findServiceActor()
service ! stop
}
case result: PizzaCustomerBaked => {
user ! result
}
case PizzaCustomerPing => sender() ! PizzaCustomerPong
case MemberUp(m) if m.hasRole("chef") => nodes += m.address
case ReachableMember(m) if m.hasRole("chef") => nodes += m.address
case otherMemberEvent: MemberEvent => nodes -= otherMemberEvent.member.address
case UnreachableMember(m) => nodes -= m.address
}
private def findServiceActor(): ActorSelection = {
// for load balance, select random master proxy
val address = nodes.toIndexedSeq(ThreadLocalRandom.current.nextInt(nodes.size))
context.actorSelection(RootActorPath(address) / servicePathElements)
}
}
示例12: RoomClientActor
//设置package包名称以及导入依赖的类
package actors
import java.util.UUID
import akka.actor.{Actor, ActorLogging, ActorRef, ActorSelection, Props}
import commands.{ListPublicRoomsCommand, NewMessageCommand, UserJoinRoomCommand, UserLeftRoomCommand}
import events.{JoinedChannelEvent, NewMessageEvent, RoomEventType}
import json.{IncomingRoomMessage, OutgoingRoomMessage}
import org.joda.time.DateTime
class RoomClientActor(actorRef: ActorRef, userId: String) extends Actor with ActorLogging {
var roomMasterActor: ActorSelection = _
@scala.throws[Exception](classOf[Exception])
override def preStart(): Unit = {
super.preStart()
roomMasterActor = context.actorSelection("/user/" + RoomMasterActor.getClass.getSimpleName)
}
override def receive: Receive = {
case msg: IncomingRoomMessage => processIncomingRoomMessage(msg)
case msg: JoinedChannelEvent => actorRef ! new OutgoingRoomMessage(msg.channelId, msg.userId, RoomEventType.JOIN.toString, None, DateTime.now().getMillis)
case msg: NewMessageEvent => actorRef ! new OutgoingRoomMessage(msg.from, msg.from, RoomEventType.MESSAGE.toString, Option(msg.text), msg.timestamp)
case msg: Any => unhandled(msg)
}
def processIncomingRoomMessage(msg: IncomingRoomMessage): Unit = {
val eventType = RoomEventType.withName(msg.eventType)
eventType match {
case RoomEventType.JOIN => {
roomMasterActor ! new UserJoinRoomCommand(msg.roomId, userId)
}
case RoomEventType.MESSAGE => {
msg.text match {
case text: Some[String] => roomMasterActor ! new NewMessageCommand(userId, msg.roomId, msg.text.get, UUID.randomUUID().toString, DateTime.now.getMillis)
case None => sender() ! "Invalid message"
}
}
case RoomEventType.LEAVE => roomMasterActor ! new UserLeftRoomCommand(msg.roomId, userId)
case RoomEventType.LIST => roomMasterActor ! new ListPublicRoomsCommand
}
}
}
object RoomClientActor {
def props(actorRef: ActorRef, userId: String) = Props(new RoomClientActor(actorRef, userId))
}
示例13: DestinationsFeedWSConnection
//设置package包名称以及导入依赖的类
package services
import akka.actor.{Actor, ActorRef, ActorSelection, Props}
import play.api.Logger
import play.api.libs.json.JsValue
class DestinationsFeedWSConnection(destinationFeedManager: ActorSelection, out: ActorRef)
extends Actor with DestinationFeedProtocolParser with FeedResponseGenerator {
def receive = {
case jsonRequest: JsValue =>
parseAndHandle(jsonRequest)
case SubscriptionFeed(json) =>
out ! constructJsonResponse(LiveFeed(json))
case other =>
println("UNHANDLED MESSAGE")
println(other)
}
override def postStop() {
Logger.info("Client unsubscribing from stream")
destinationFeedManager ! UnSubscribeToFeed
}
private def parseAndHandle(jsonRequest: JsValue) = {
handleRequest(parseRequest(jsonRequest))
}
private def handleRequest(request: DestinationFeedProtocol) = request match {
case DestinationFeedSubscriptionRequest =>
out ! constructJsonResponse(Subscribing)
destinationFeedManager ! SubscribeToFeed
case DestinationFeedUnSubscriptionRequest =>
destinationFeedManager ! UnSubscribeToFeed
case DestinationFeedUnknownRequest =>
out ! constructJsonResponse(UnknownRequest)
}
}
object DestinationsFeedWSConnection {
def props(destinationFeedManager: ActorSelection, out: ActorRef) =
Props(new DestinationsFeedWSConnection(destinationFeedManager, out))
}
示例14: TaxRateProducer
//设置package包名称以及导入依赖的类
package scb.tpcdi
import akka.actor.{Actor, ActorLogging, ActorSelection}
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
class TaxRateProducer extends Actor with ActorLogging {
import context.dispatcher
implicit val timeout = Timeout(2 seconds)
var da = None : Option[ActorSelection] // DataAccess actor with circuit breaker
val rnd = new java.util.Random()
case class Tick()
val ticker =
context.system.scheduler.schedule(5 seconds, 500 millis, self, Tick())
override def postStop() = ticker.cancel()
def receive = {
case Tick() =>
da match {
case None =>
da = Some(context.actorSelection("/user/dataaccess/singleton"))
case Some(da) =>
ask(da, nextTaxRate()) onFailure {
case e => log.error("Error: {}", e)
}
}
}
def nextTaxRate(): TaxRate = {
TaxRate("US1",
"U.S. Income Tax Bracket for the poor",
rnd.nextDouble())
//(math floor rnd.nextDouble() * 1E5) / 1E2)
}
}
示例15: SignonActor
//设置package包名称以及导入依赖的类
package operation.trivia.actors
import akka.actor.{Actor, ActorSelection}
import akka.event.Logging
import operation.trivia.entities._
import scala.collection.mutable.ArrayBuffer
class SignonActor extends Actor {
private[SignonActor] val players: ArrayBuffer[Player] = ArrayBuffer[Player]()
private[SignonActor] val log = Logging(context.system, this)
private[SignonActor] val hostActorSelection =
context.system.actorSelection("akka.tcp://[email protected]:2553/user/hostActor")
override def receive: Receive = {
case SignOn(p:Player) =>
log.debug("Signing on player: {}", p)
players += p
if (players.nonEmpty) {
log.debug("Single player signed on, starting game")
hostActorSelection ! GameStart
}
case SignOff(p:Player) =>
//No more players, stop the game
log.debug("Signing off player: {}", p)
players -= p
if (players.isEmpty) {
log.debug("No players signed on, stopping game")
hostActorSelection ! GameStop
}
}
}