本文整理汇总了Scala中akka.pattern.ask类的典型用法代码示例。如果您正苦于以下问题:Scala ask类的具体用法?Scala ask怎么用?Scala ask使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ask类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Ctask
//设置package包名称以及导入依赖的类
package com.ctask.engine
import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.pattern.ask
import com.ctask.engine.CommandExecutor.{Command, InvalidCommand}
import com.ctask.engine.Ctask._
import com.ctask.messages.{CommandLine, ServerError}
import scala.concurrent.ExecutionContext.Implicits.global
import com.ctask.messages.Response
import scala.concurrent.duration._
import scala.concurrent.Future
import scala.util.{Failure, Success}
object Ctask {
val pongMsg = "I am the Ctask actor!"
private def logIgnore: Receive = {
case msg => log.warning(s"Received and ignored msg $msg")
}
private def stopCommandExecutor: Unit = {
context.stop(commandExecutor)
log.debug("Stopped command executor")
}
}
示例2: PinnedActorSpec
//设置package包名称以及导入依赖的类
package akka.actor.dispatch
import java.util.concurrent.{ CountDownLatch, TimeUnit }
import akka.testkit._
import akka.actor.{ Props, Actor }
import akka.testkit.AkkaSpec
import org.scalatest.BeforeAndAfterEach
import akka.dispatch.{ PinnedDispatcher, Dispatchers }
import scala.concurrent.Await
import akka.pattern.ask
object PinnedActorSpec {
val config = """
pinned-dispatcher {
executor = thread-pool-executor
type = PinnedDispatcher
}
"""
class TestActor extends Actor {
def receive = {
case "Hello" ? sender() ! "World"
case "Failure" ? throw new RuntimeException("Expected exception; to test fault-tolerance")
}
}
}
@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class PinnedActorSpec extends AkkaSpec(PinnedActorSpec.config) with BeforeAndAfterEach with DefaultTimeout {
import PinnedActorSpec._
private val unit = TimeUnit.MILLISECONDS
"A PinnedActor" must {
"support tell" in {
var oneWay = new CountDownLatch(1)
val actor = system.actorOf(Props(new Actor { def receive = { case "OneWay" ? oneWay.countDown() } }).withDispatcher("pinned-dispatcher"))
val result = actor ! "OneWay"
assert(oneWay.await(1, TimeUnit.SECONDS))
system.stop(actor)
}
"support ask/reply" in {
val actor = system.actorOf(Props[TestActor].withDispatcher("pinned-dispatcher"))
assert("World" === Await.result(actor ? "Hello", timeout.duration))
system.stop(actor)
}
}
}
示例3: ForwardActorSpec
//设置package包名称以及导入依赖的类
package akka.actor
import language.postfixOps
import akka.testkit._
import scala.concurrent.duration._
import akka.actor.Actor._
import scala.concurrent.Await
import akka.pattern.{ ask, pipe }
object ForwardActorSpec {
val ExpectedMessage = "FOO"
def createForwardingChain(system: ActorSystem): ActorRef = {
val replier = system.actorOf(Props(new Actor {
def receive = { case x ? sender() ! x }
}))
def mkforwarder(forwardTo: ActorRef) = system.actorOf(Props(
new Actor {
def receive = { case x ? forwardTo forward x }
}))
mkforwarder(mkforwarder(mkforwarder(replier)))
}
}
@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class ForwardActorSpec extends AkkaSpec {
import ForwardActorSpec._
implicit val ec = system.dispatcher
"A Forward Actor" must {
"forward actor reference when invoking forward on tell" in {
val replyTo = system.actorOf(Props(new Actor { def receive = { case ExpectedMessage ? testActor ! ExpectedMessage } }))
val chain = createForwardingChain(system)
chain.tell(ExpectedMessage, replyTo)
expectMsg(5 seconds, ExpectedMessage)
}
"forward actor reference when invoking forward on ask" in {
val chain = createForwardingChain(system)
chain.ask(ExpectedMessage)(5 seconds) pipeTo testActor
expectMsg(5 seconds, ExpectedMessage)
}
}
}
示例4: PaymentMethods
//设置package包名称以及导入依赖的类
package controllers
import java.util.UUID
import actors.{SessionActorMessages, MainActorMessages}
import akka.actor.ActorRef
import com.gilt.akk.cluster.api.test.v0.models.PaymentMethod
import scala.concurrent.Future
import play.api.libs.json._
import com.gilt.akk.cluster.api.test.v0.models.json._
import play.api.mvc._
import akka.pattern.ask
class PaymentMethods (mainActor: ActorRef) extends BaseController {
def get(uuidStr: String) = Action.async { request =>
val uuid = UUID.fromString(uuidStr)
for{
actorRef <- ask(mainActor, MainActorMessages.FindActor(uuid)).mapTo[ActorRef]
response <- ask(actorRef, SessionActorMessages.PaymentMethods(uuid)).mapTo[Future[Seq[PaymentMethod]]]
paymentMethods <- response
} yield {
Ok(Json.toJson(paymentMethods))
}
}
}
示例5: handleProof
//设置package包名称以及导入依赖的类
package wow.auth.handlers
import akka.pattern.ask
import akka.util.Timeout
import wow.auth.AccountsState
import wow.auth.AccountsState.IsOnline
import wow.auth.data.Account
import wow.auth.protocol.AuthResults
import wow.auth.protocol.packets.{ClientLogonProof, ServerLogonProof, ServerLogonProofFailure, ServerLogonProofSuccess}
import wow.auth.session.AuthSession.EventIncoming
import wow.auth.session._
import wow.auth.utils.PacketSerializer
import scala.concurrent.Await
import scala.concurrent.duration._
trait LogonProofHandler {
this: AuthSession =>
def handleProof: StateFunction = {
case Event(EventIncoming(bits), ChallengeData(login, srp6Identity, srp6Challenge)) =>
log.debug("Received proof")
val packet = PacketSerializer.deserialize[ClientLogonProof](bits)
log.debug(packet.toString)
srp6.verify(login, packet.clientKey, packet.clientProof, srp6Identity, srp6Challenge) match {
case Some(srp6Validation) =>
val accountState = context.actorSelection(AccountsState.ActorPath)
implicit val timeout = Timeout(5 seconds)
val askIsOnline = (accountState ? IsOnline(login)).mapTo[Boolean]
val isOnline = Await.result(askIsOnline, timeout.duration)
if (isOnline) {
sendPacket(ServerLogonProof(AuthResults.FailAlreadyOnline, None, Some(ServerLogonProofFailure())))
goto(StateFailed) using NoData
} else {
Account.saveSessionKey(login, srp6Validation.sharedKey)
sendPacket(ServerLogonProof(AuthResults.Success,
Some(ServerLogonProofSuccess(srp6Validation.serverProof)),
None))
goto(StateRealmlist) using NoData
}
case None =>
sendPacket(ServerLogonProof(AuthResults.FailUnknownAccount, None, Some(ServerLogonProofFailure())))
goto(StateFailed) using NoData
}
}
}
示例6: ActorTest
//设置package包名称以及导入依赖的类
package org.argus.amandroid.concurrent
import org.scalatest.{FlatSpec, Matchers}
import org.argus.jawa.core.util._
import akka.actor._
import akka.pattern.ask
import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory
import org.argus.amandroid.concurrent.util.Recorder
import org.argus.amandroid.core.decompile.ConverterUtil
import org.argus.amandroid.plugin.TaintAnalysisModules
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.{global => sc}
import scala.language.postfixOps
class ActorTest extends FlatSpec with Matchers {
"ICC_Implicit_Src_Sink" should "successfully resolved" in {
val res = runActor(getClass.getResource("/icc-bench/IccHandling/icc_implicit_src_sink.apk").getPath)
assert(
res.isDefined &&
res.get.isInstanceOf[Success] &&
res.get.asInstanceOf[SecurityEngineSuccResult].sr.isDefined &&
res.get.asInstanceOf[SecurityEngineSuccResult].sr.get.isInstanceOf[TaintAnalysisResult])
}
private def runActor(apkFile: String): Option[SecurityEngineResult] = {
val _system = ActorSystem("ActorTest", ConfigFactory.load)
val apkUri = FileUtil.toUri(apkFile)
val outputUri = FileUtil.toUri(apkFile.substring(0, apkFile.length - 4))
val supervisor = _system.actorOf(Props(classOf[AmandroidSupervisorActor], Recorder(outputUri)), name = "AmandroidSupervisorActor")
val future = supervisor.ask(AnalysisSpec(apkUri, outputUri, None, removeSupportGen = true, forceDelete = true))(2 minutes).mapTo[PointsToAnalysisResult].recover{
case ex: Exception =>
PointsToAnalysisFailResult(apkUri, 2, 1, ex)
}
val ptr = Await.result(future, 3 minutes)
var result: Option[SecurityEngineResult] = None
ptr match {
case ptar: PointsToAnalysisResult with Success =>
val future = supervisor.ask(SecurityEngineData(ptar, TaintAnalysisSpec(TaintAnalysisModules.DATA_LEAKAGE)))(1 minutes).mapTo[SecurityEngineResult].recover {
case ex: Exception =>
SecurityEngineFailResult(ptar.fileUri, ex)
}
result = Some(Await.result(future, 2 minutes))
case _ =>
}
_system.terminate()
ConverterUtil.cleanDir(outputUri)
result
}
}
示例7: InstanceCreationHandlerAndUpdaterDelegate
//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.task.tracker.impl
//scalastyle:off
import akka.Done
import akka.actor.ActorRef
import akka.util.Timeout
import mesosphere.marathon.core.base.Clock
import mesosphere.marathon.core.instance.Instance
import mesosphere.marathon.core.instance.update.{ InstanceUpdateEffect, InstanceUpdateOperation }
import mesosphere.marathon.core.instance.update.InstanceUpdateOperation.ReservationTimeout
import mesosphere.marathon.core.task.tracker.impl.InstanceTrackerActor.ForwardTaskOp
import mesosphere.marathon.core.task.tracker.{ InstanceCreationHandler, InstanceTrackerConfig, TaskReservationTimeoutHandler, TaskStateOpProcessor }
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.util.control.NonFatal
//scalastyle:on
// TODO(PODS): rename to instance...
private[tracker] class InstanceCreationHandlerAndUpdaterDelegate(
clock: Clock,
conf: InstanceTrackerConfig,
instanceTrackerRef: ActorRef)
extends InstanceCreationHandler with TaskStateOpProcessor with TaskReservationTimeoutHandler {
import scala.concurrent.ExecutionContext.Implicits.global
private[impl] implicit val timeout: Timeout = conf.internalTaskUpdateRequestTimeout().milliseconds
override def process(stateOp: InstanceUpdateOperation): Future[InstanceUpdateEffect] = {
taskUpdate(stateOp.instanceId, stateOp)
}
override def created(taskStateOp: InstanceUpdateOperation): Future[Done] = {
process(taskStateOp).map(_ => Done)
}
override def terminated(stateOp: InstanceUpdateOperation.ForceExpunge): Future[Done] = {
process(stateOp).map(_ => Done)
}
override def timeout(stateOp: ReservationTimeout): Future[_] = {
process(stateOp)
}
private[this] def taskUpdate(
instanceId: Instance.Id, stateOp: InstanceUpdateOperation): Future[InstanceUpdateEffect] = {
import akka.pattern.ask
val deadline = clock.now + timeout.duration
val op: ForwardTaskOp = InstanceTrackerActor.ForwardTaskOp(deadline, instanceId, stateOp)
(instanceTrackerRef ? op).mapTo[InstanceUpdateEffect].recover {
case NonFatal(e) =>
throw new RuntimeException(s"while asking for $op on runSpec [${instanceId.runSpecId}] and $instanceId", e)
}
}
}
示例8: Main
//设置package包名称以及导入依赖的类
package com.bob.akka.supervision
import akka.actor.{ActorSystem, Props}
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration.{Duration, _}
import scala.concurrent.{Await, Future}
object Main {
def main(args: Array[String]): Unit = {
val system = ActorSystem("calculator-system")
val calculatorService = system.actorOf(Props[ArithmeticService], "arithmetic-service")
def calculate(expr: Expression): Future[Int] = {
implicit val timeoute = Timeout(1.second)
(calculatorService ? expr).mapTo[Int]
}
// (3 + 5) / (2 * (1 + 1))
val task = Divide(
Add(Const(3), Const(5)),
Multiply(
Const(2),
Add(Const(1), Const(1))
)
)
val result = Await.result(calculate(task), 5.second)
println(s"Got result: $result")
Await.ready(system.terminate(), Duration.Inf)
}
}
示例9: Application
//设置package包名称以及导入依赖的类
package controllers
import akka.actor._
import akka.pattern.AskTimeoutException
import com.google.inject.name.Named
import com.google.inject.{Inject, Singleton}
import play.api._
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.mvc._
import scala.concurrent.Future
import scalaz.\/.left
import scalaz.{-\/, \/-}
import actors.Library
import actors.Library.{RequestBooks, BookData}
import entities.Book
import forms.SearchForm
@Singleton
class Application @Inject()(system: ActorSystem,
@Named("ndl-client-actor") ndlClient: ActorRef)
extends Controller {
import akka.pattern.ask
import scala.concurrent.duration._
def index = Action(Ok(views.html.index("Simple OPAC")))
val bookForm = Form(
mapping(
"title" -> optional(text),
"author" -> optional(text),
"any" -> optional(text),
"count" -> optional(number(min = 1, max = 200))
)(SearchForm.apply)(SearchForm.unapply)
)
implicit val bookToJson = Json.writes[Book]
implicit val timeout: akka.util.Timeout = 1 minute
lazy val libraryActor = system.actorOf(Library.props)
def books = Action.async { implicit req =>
bookForm.bindFromRequest.fold(
formWithError => {
Future.successful(BadRequest("invalid request"))
},
{
case validForm => (try {
libraryActor.ask(RequestBooks(validForm, ndlClient)).mapTo[BookData].map(_.books)
} catch {
case e: AskTimeoutException => Future.successful(left(s"Server Error: \n$e"))
case _ => Future.successful(left("Something wrong..."))
}).map {
case \/-(books) => Ok(Json.toJson(books))
case -\/(msg) => InternalServerError(msg)
}
}
)
}
}
示例10: RestInterface
//设置package包名称以及导入依赖的类
package com.michalplachta.shoesorter.api
import akka.actor.{ ActorRef, ActorSystem }
import akka.event.slf4j.SLF4JLogging
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.server.{ HttpApp, Route }
import akka.pattern.ask
import com.michalplachta.shoesorter.Domain.{ Container, Junction }
import com.michalplachta.shoesorter.Messages.{ Go, WhereShouldIGo }
import com.monsanto.arch.kamon.prometheus.akka_http.AkkaHttpEndpoint
import kamon.Kamon
import kamon.trace.Tracer
import scala.concurrent.duration._
class RestInterface(decider: ActorRef, exposedPort: Int)(implicit system: ActorSystem) extends SLF4JLogging {
object WebServer extends HttpApp {
def route: Route =
path("junctions" / IntNumber / "decisionForContainer" / IntNumber) { (junctionId, containerId) ?
get {
complete {
Tracer.withNewContext("DecisionRequest") {
val junction = Junction(junctionId)
val container = Container(containerId)
Kamon.metrics.counter(
"api_http_requests_total",
Map("junctionId" ? junctionId.toString, "containerId" ? containerId.toString)
).increment()
log.info(s"Request for junction $junctionId and container $containerId")
decider.ask(WhereShouldIGo(junction, container))(5.seconds).mapTo[Go]
}
}
}
} ~ path("metrics") {
AkkaHttpEndpoint(system).route
}
}
WebServer.startServer("0.0.0.0", exposedPort)
}
示例11: UserServiceImpl
//设置package包名称以及导入依赖的类
package scalafiddle.server.models.services
import java.util.UUID
import javax.inject.{Inject, Named}
import akka.actor._
import akka.pattern.ask
import akka.util.Timeout
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.providers.CommonSocialProfile
import play.api.Logger
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.util.{Success, Try}
import scalafiddle.server._
import scalafiddle.server.models.User
class UserServiceImpl @Inject()(@Named("persistence") persistence: ActorRef) extends UserService {
implicit val timeout = Timeout(15.seconds)
val log = Logger(getClass)
override def save(profile: CommonSocialProfile): Future[User] = {
log.debug(s"User $profile logged in")
val user = User(UUID.randomUUID().toString,
profile.loginInfo,
profile.firstName,
profile.lastName,
profile.fullName,
profile.email,
profile.avatarURL,
true)
ask(persistence, AddUser(user)).mapTo[Try[User]].map {
case Success(u) =>
u
case _ =>
throw new Exception("Unable to save user")
}
}
override def retrieve(loginInfo: LoginInfo): Future[Option[User]] = {
ask(persistence, FindUserLogin(loginInfo)).mapTo[Try[User]].map {
case Success(user) =>
Some(user)
case _ =>
None
}
}
}
示例12: PresenceExtensionImpl
//设置package包名称以及导入依赖的类
package im.actor.server.presences
import akka.actor._
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.Future
import scala.concurrent.duration._
sealed trait PresenceExtension extends Extension
class PresenceExtensionImpl(system: ActorSystem) extends PresenceExtension {
import PresenceManager._
import Presences._
import system.dispatcher
implicit val timeout: Timeout = Timeout(20.seconds)
private val region = PresenceManagerRegion.startRegion()(system)
def subscribe(userId: Int, consumer: ActorRef): Future[Unit] = {
region.ref.ask(Envelope(userId, Subscribe(consumer))).mapTo[SubscribeAck].map(_ ? ())
}
def subscribe(userIds: Set[Int], consumer: ActorRef): Future[Unit] =
Future.sequence(userIds map (subscribe(_, consumer))) map (_ ? ())
def unsubscribe(userId: Int, consumer: ActorRef): Future[Unit] = {
region.ref.ask(Envelope(userId, Unsubscribe(consumer))).mapTo[UnsubscribeAck].map(_ ? ())
}
def presenceSetOnline(userId: Int, authId: Long, timeout: Long): Unit = {
region.ref ! Envelope(userId, UserPresenceChange(Online, authId, timeout))
}
def presenceSetOffline(userId: Int, authId: Long, timeout: Long): Unit = {
region.ref ! Envelope(userId, UserPresenceChange(Offline, authId, timeout))
}
}
object PresenceExtension extends ExtensionId[PresenceExtensionImpl] with ExtensionIdProvider {
override def lookup = PresenceExtension
override def createExtension(system: ExtendedActorSystem) = new PresenceExtensionImpl(system)
}
示例13: GroupPresenceExtensionImpl
//设置package包名称以及导入依赖的类
package im.actor.server.presences
import akka.actor._
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.Future
import scala.concurrent.duration._
sealed trait GroupPresenceExtension extends Extension
class GroupPresenceExtensionImpl(system: ActorSystem) extends GroupPresenceExtension {
import GroupPresenceManager._
import system.dispatcher
implicit val timeout: Timeout = Timeout(20.seconds)
private val region = GroupPresenceManagerRegion.startRegion()(system)
def subscribe(groupId: Int, consumer: ActorRef): Future[Unit] = {
region.ref.ask(Envelope(groupId, Subscribe(consumer))).mapTo[SubscribeAck].map(_ ? ())
}
def subscribe(groupIds: Set[Int], consumer: ActorRef): Future[Unit] =
Future.sequence(groupIds map (subscribe(_, consumer))) map (_ ? ())
def unsubscribe(groupId: Int, consumer: ActorRef): Future[Unit] = {
region.ref.ask(Envelope(groupId, Unsubscribe(consumer))).mapTo[UnsubscribeAck].map(_ ? ())
}
def notifyGroupUserAdded(groupId: Int, userId: Int): Unit = {
region.ref ! Envelope(groupId, UserAdded(userId))
}
def notifyGroupUserRemoved(groupId: Int, userId: Int): Unit = {
region.ref ! Envelope(groupId, UserRemoved(userId))
}
}
object GroupPresenceExtension extends ExtensionId[GroupPresenceExtensionImpl] with ExtensionIdProvider {
override def lookup = GroupPresenceExtension
override def createExtension(system: ExtendedActorSystem) = new GroupPresenceExtensionImpl(system)
}
示例14: 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
}
}
示例15: StoryActor
//设置package包名称以及导入依赖的类
package com.benoj.janus.workunits
import akka.actor.Props
import akka.pattern.ask
import akka.util.Timeout
import com.benoj.janus.PersistentLoggingActor
import com.benoj.janus.behavior.Attributes.implicits._
import com.benoj.janus.behavior.Created.Create
import com.benoj.janus.behavior._
import com.benoj.janus.organisation.IdActor.Messages.{GetNextId, Id}
import com.benoj.janus.suppliers.Actors.IdSupplier
import com.benoj.janus.workflow.WorkflowActor.Commands.AddWorkUnit
import com.benoj.janus.workflow.WorkflowActor.WorkflowStage
import com.benoj.janus.workunits.StoryActor.Messages.CreateTask
import scala.concurrent.ExecutionContext
import scala.util.Success
class StoryActor(name: String = "", description: String = "")
(implicit val timeout: Timeout, val executionContext: ExecutionContext, idSupplier: IdSupplier)
extends PersistentLoggingActor
with JanusEventProcessing
with Attributes
with Watchable
with Assignee
with WorkFlow
with Created {
log.info("Starting Story Actor")
override def attributes = Map("name" -> name, "description" -> description)
override val stages = Seq(WorkflowStage("analysis"), WorkflowStage("doing"))
override def postCreation = {
case CreateTask(taskName, taskDescription) =>
log.info("Story received create task")
val responder = sender()
idSupplier.actor ? GetNextId onComplete {
case Success(Id(id)) => workFlow ? AddWorkUnit(id) onSuccess {
case _ => context.actorOf(TaskActor.props(taskName, taskDescription), s"task-$id") tell(Create(id), responder)
}
case [email protected]_ =>
log.error(s"Unable to get next ID. Cause $e")
}
}
}
object StoryActor {
def props(name: String = "", description: String = "")
(implicit timeout: Timeout, executionContext: ExecutionContext, idSupplier: IdSupplier) = Props(new StoryActor(name, description))
object Messages {
case class CreateTask(name: String = "", description: String = "")
}
}