本文整理汇总了Scala中akka.actor.ActorRefFactory类的典型用法代码示例。如果您正苦于以下问题:Scala ActorRefFactory类的具体用法?Scala ActorRefFactory怎么用?Scala ActorRefFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ActorRefFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: GoogleBooksClient
//设置package包名称以及导入依赖的类
package org.packtpublishing.integrations
import akka.actor.ActorRefFactory
import scala.language.postfixOps
import org.packtpublishing.web.BookSearchResult
import spray.http._
import spray.http.StatusCodes.{OK, BadRequest}
import spray.client.pipelining._
import scala.concurrent.Future
import scala.concurrent.duration.Duration._
import scala.concurrent.duration._
import akka.util.Timeout
class GoogleBooksClient(implicit actorRefFactory: ActorRefFactory) {
import scala.concurrent.ExecutionContext.Implicits.global
import spray.httpx.SprayJsonSupport._
import org.packtpublishing.web.BooksJsonProtocol._
implicit val timeout: Timeout = 5 seconds
val pipeline: HttpRequest => Future[BookSearchResult] =
sendReceive ~>
unmarshal[BookSearchResult]
def uri(query: String) =
Uri("https://www.googleapis.com/books/v1/volumes")
.withQuery(("q", query))
def findBooks(query: String) = {
pipeline(Get(uri(query))) map(_.items.map(_.volumeInfo))
}
}
示例2: LeadershipModuleImpl
//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.leadership
import akka.actor.{ ActorRef, ActorRefFactory, Props }
import mesosphere.marathon.core.leadership.impl._
trait LeadershipModule {
private[leadership] class LeadershipModuleImpl(
actorRefFactory: ActorRefFactory) extends LeadershipModule {
private[this] var whenLeaderRefs = Set.empty[ActorRef]
private[this] var started: Boolean = false
override def startWhenLeader(props: Props, name: String): ActorRef = {
require(!started, s"already started: $name")
val proxyProps = WhenLeaderActor.props(props)
val actorRef = actorRefFactory.actorOf(proxyProps, name)
whenLeaderRefs += actorRef
actorRef
}
override def coordinator(): LeadershipCoordinator = coordinator_
private[this] lazy val coordinator_ = {
require(!started, "already started")
started = true
val props = LeadershipCoordinatorActor.props(whenLeaderRefs)
val actorRef = actorRefFactory.actorOf(props, "leaderShipCoordinator")
new LeadershipCoordinatorDelegate(actorRef)
}
}
示例3: doSendReceive
//设置package包名称以及导入依赖的类
package com.sky.workshop.spray
import akka.actor.{ActorRefFactory, ActorSystem}
import akka.util.Timeout
import spray.client.pipelining._
import spray.http._
import spray.httpx.unmarshalling._
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
trait RestClient {
implicit val system: ActorSystem
implicit lazy val executionContext: ExecutionContext = system.dispatcher
def doSendReceive(implicit refFactory: ActorRefFactory, executionContext: ExecutionContext): SendReceive = sendReceive
def webGet[Rs: FromResponseUnmarshaller](path: String): Future[Rs] = {
Get(path) ~> pipeline
}
def webPost[Rs: FromResponseUnmarshaller](req: HttpRequest): Future[Rs] = {
req ~> pipeline
}
def pipeline[T: FromResponseUnmarshaller]: HttpRequest => Future[T] = {
implicit val timeout: Timeout = Timeout(2 seconds)
(
doSendReceive
~> unmarshal[T]
)
}
}
示例4: props
//设置package包名称以及导入依赖的类
package utils
import akka.actor.{ActorRef, ActorRefFactory, Props}
trait PropFactory {
def props(args: Any*): Props
}
trait ActorFactory {
def apply[T <: PropFactory](ref: T, context: ActorRefFactory, name: String, args: Any*): ActorRef
}
object ActorFactory extends ActorFactory {
def apply[T <: PropFactory](ref: T, context: ActorRefFactory, name: String, args: Any*): ActorRef = {
context.actorOf(ref.props(args: _*), name)
}
}
示例5: EtagServiceSpec
//设置package包名称以及导入依赖的类
package actor
import akka.actor.ActorRefFactory
import org.specs2.mutable.Specification
import spray.http.StatusCodes._
import spray.http.HttpHeaders._
import spray.testkit.Specs2RouteTest
class EtagServiceSpec extends Specification with Specs2RouteTest with EtagService {
def actorRefFactory: ActorRefFactory = system
import json.Json4sSupport._
"EtagService" should {
"""return status: "ok" for GET requests to the root path""" in {
Get().withHeaders(ETag("406161ad525c9bdf02a21db721f2ffeb")) ~> routes ~> check {
status === OK
val response = responseAs[FooResponse]
response.status must_== "ok"
response.method must_== "GET"
response.headerCount must_== 1
}
}
"leave GET requests to other paths unhandled" in {
Get("/unhandled") ~> routes ~> check {
handled must beFalse
}
}
"return a MethodNotAllowed error for PUT requests to the root path" in {
Put() ~> sealRoute(routes) ~> check {
status === MethodNotAllowed
// responseAs[String] === "HTTP method not allowed, supported methods: GET" // TODO fix
}
}
}
}
示例6: WebSocketWorker
//设置package包名称以及导入依赖的类
package nestapp.websocketserver
import akka.actor.{ActorRef, ActorRefFactory}
import spray.can.websocket
import spray.can.websocket.FrameCommandFailed
import spray.can.websocket.frame.{BinaryFrame, TextFrame}
import spray.http.HttpRequest
import spray.routing.HttpServiceActor
class WebSocketWorker(val serverConnection: ActorRef) extends HttpServiceActor with websocket.WebSocketServerWorker {
override def receive = handshaking orElse businessLogicNoUpgrade orElse closeLogic
def businessLogic: Receive = {
// just bounce frames back for Autobahn testsuite
case [email protected](_: BinaryFrame | _: TextFrame) => sender() ! x
case Push(msg) => send(TextFrame(msg))
case x: FrameCommandFailed => log.error("frame command failed", x)
case x: HttpRequest => // do something
}
def businessLogicNoUpgrade: Receive = {
implicit val refFactory: ActorRefFactory = context
runRoute {
getFromResourceDirectory("webapp")
}
}
}
示例7: OrderingExecutor
//设置package包名称以及导入依赖的类
package com.pagerduty.scheduler.akka
import akka.actor.{ActorRef, ActorRefFactory, Props, Stash}
import com.pagerduty.scheduler.model.{Task, TaskKey}
import scala.collection.immutable.SortedMap
object OrderingExecutor {
class OrderingExecutor(
orderingId: Task.OrderingId,
partitionExecutor: ActorRef,
taskExecutorFactory: (ActorRefFactory, Task, ActorRef) => ActorRef)
extends ExtendedLoggingFSM[OrderingExecutor.State, OrderingExecutor.Data]
with Stash {
import OrderingExecutor._
import PartitionExecutor._
startWith(Idle, Data(SortedMap.empty))
override val supervisorStrategy = Supervision.AlwaysEscalateStrategy
when(Idle) {
case Event(ExecuteOrderingTask(task), data) if task.orderingId == orderingId => {
assert(data.taskQueue.isEmpty)
execute(task)
goto(Executing)
}
}
when(Executing) {
case Event(ExecuteOrderingTask(task), data) if task.orderingId == orderingId => {
stay() using Data(data.taskQueue + (task.taskKey -> task))
}
case Event(TaskExecuted(taskKey), data) if taskKey.orderingId == orderingId => {
partitionExecutor ! OrderingTaskExecuted(taskKey)
if (data.taskQueue.isEmpty) {
goto(Idle)
} else {
val (taskKey, task) = data.taskQueue.head
val remaining = data.taskQueue.tail
execute(task)
stay() using Data(remaining)
}
}
}
def execute(task: Task): Unit = {
taskExecutorFactory(context, task, context.self)
}
}
示例8: PartitionSupervisorSpec
//设置package包名称以及导入依赖的类
package com.pagerduty.scheduler.akka
import akka.actor.{ActorRefFactory, Props}
import akka.testkit.TestProbe
import com.pagerduty.scheduler.specutil.{ActorPathFreeSpec, TaskFactory}
import com.pagerduty.scheduler.Scheduler
import org.scalamock.scalatest.PathMockFactory
class PartitionSupervisorSpec extends ActorPathFreeSpec("PartitionSupervisorSpec") with PathMockFactory {
val settings = Settings()
val partitionId = 1
val tasks = TaskFactory.makeTasks(3)
val queueContext = QueueContext(
taskScheduleDao = null,
taskStatusDao = null,
taskExecutorService = null,
logging = stub[Scheduler.Logging]
)
"PartitionSupervisor should" - {
val taskPersistence = TestProbe()
val taskPersistenceFactory = (_: ActorRefFactory, args: TaskPersistenceArgs) => {
args.partitionId shouldEqual partitionId
taskPersistence.testActor
}
val partitionSupervisorProps = Props(
new PartitionSupervisor(
settings,
queueContext,
partitionId,
taskPersistenceFactory
)
)
val paritionsSupervisor = system.actorOf(partitionSupervisorProps)
taskPersistence.expectMsgType[TaskPersistence.LoadTasks]
"forward PersistTask messages" in {
val msg = TaskPersistence.PersistTasks(tasks)
paritionsSupervisor ! msg
taskPersistence expectMsg msg
}
}
}
示例9: MyServiceSpec
//设置package包名称以及导入依赖的类
package com.wallace.demo.rest.sever.demo.rest
import akka.actor.ActorRefFactory
import org.specs2.mutable.Specification
import spray.testkit.Specs2RouteTest
class MyServiceSpec extends Specification with Specs2RouteTest with MyService {
def actorRefFactory: ActorRefFactory = system
"MyService" should {
"return Json String" in {
Get("/wallace") ~> myRoute ~> check {
log.info(
s"""
|[Entity]: ${response.entity.asString}
|[Entity => Option]: ${response.entity.toOption}
|[Entity => Case Class]: ${responseAs[Map[String, Int]]}
|[Message]: ${response.message}
|[Protocol]: ${response.protocol}
|[Status]: ${status.intValue}
""".stripMargin)
status.intValue mustEqual 200
response.entity.toOption.get.asString must contain("{\"Wallace\":25,\"Lina\":26,\"Lucy\":24}")
responseAs[Map[String, Int]].get("Wallace") mustEqual Some(25)
//responseAs[String] must contain("test")
}
Get("/wallace/index") ~> myRoute ~> check {
status.intValue mustEqual 200
response.entity.asString must contain("hello,world!")
}
}
}
}
示例10: Microservice
//设置package包名称以及导入依赖的类
package io.github.bszwej
import akka.actor.{ActorRefFactory, ActorSystem}
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.scalalogging.LazyLogging
import io.github.bszwej.api.HashtagEndpoint
import io.github.bszwej.core.mongo.MongoTweetCollectionProvider
import io.github.bszwej.core.repository.MongoTweetRepository
import io.github.bszwej.core.twitter.TwitterStreamProvider
import io.github.bszwej.core.{HashtagManagerActor, TweetCollectorActor}
import scala.concurrent.ExecutionContextExecutor
object Microservice extends LazyLogging with TwitterStreamProvider {
def main(args: Array[String]): Unit = {
implicit val system: ActorSystem = ActorSystem()
implicit val materializer: ActorMaterializer = ActorMaterializer()
implicit val context: ExecutionContextExecutor = system.dispatcher
val tweetRepository = new MongoTweetRepository(MongoTweetCollectionProvider.collection)
val tweetCollectorMaker =
(hashtag: String, f: ActorRefFactory) ?
f.actorOf(TweetCollectorActor.props(hashtag, twitterStream, tweetRepository), hashtag)
val hashtagManagerActor = system.actorOf(HashtagManagerActor.props(tweetCollectorMaker), "HashtagManagerActor")
val hashtagEndpointRoutes = new HashtagEndpoint(hashtagManagerActor).route
val port = config.getInt("server.port")
Http().bindAndHandle(hashtagEndpointRoutes, "0.0.0.0", port).onSuccess {
case _ ? logger.info(s"Server is up on port $port")
}
}
}
示例11: create
//设置package包名称以及导入依赖的类
package com.programmaticallyspeaking.ncd.chrome.domains
import akka.actor.{ActorRef, ActorRefFactory, Props}
import com.programmaticallyspeaking.ncd.infra.IdGenerator
import com.programmaticallyspeaking.ncd.ioc.Container
trait DomainFactory {
def create(domain: String): ActorRef
}
class DefaultDomainFactory(container: Container)(implicit factory: ActorRefFactory) extends DomainFactory {
private val actorNameIdGenerator = new IdGenerator("domact")
def create(domain: String): ActorRef = {
val clazz = lookupActorClass(domain)
def creator(clazz: Class[_], args: Seq[Any]) = Props(clazz, args: _*)
factory.actorOf(container.newInstance(clazz, creator), domain + "-" + actorNameIdGenerator.next)
}
private def lookupActorClass(domain: String): Class[_] = {
val className = getClass.getPackage.getName + "." + domain
val rejection = new IllegalArgumentException("Not a domain actor: " + className)
try {
val clazz = Class.forName(className)
val baseClass = classOf[DomainActor]
if (baseClass == clazz || !baseClass.isAssignableFrom(clazz)) throw rejection
clazz
} catch {
case ex: ClassNotFoundException => throw rejection
}
}
}
示例12: CapturingDomainFactory
//设置package包名称以及导入依赖的类
package com.programmaticallyspeaking.ncd.chrome.net
import akka.actor.Actor.Receive
import akka.actor.{Actor, ActorRef, ActorRefFactory, Props, Terminated}
import com.programmaticallyspeaking.ncd.chrome.domains.{DefaultDomainFactory, DomainFactory}
import com.programmaticallyspeaking.ncd.ioc.Container
import scala.collection.concurrent.TrieMap
class CapturingDomainFactory(implicit container: Container, factory: ActorRefFactory) extends DomainFactory {
private val defaultFactory = new DefaultDomainFactory(container)
private var actorMustNotExist = false
private val actors = TrieMap[String, ActorRef]()
private val watcher = factory.actorOf(Props(new ActorWatcher))
def actorByName(name: String): Option[ActorRef] = actors.get(name)
def requireNoOldActor(): Unit = {
actorMustNotExist = true
}
override def create(domain: String): ActorRef = {
actors.get(domain) match {
case Some(ar) if actorMustNotExist => throw new IllegalStateException("Found an old domain actor: " + ar)
case _ => // noop
}
val actor = defaultFactory.create(domain)
watcher ! actor
actors(domain) = actor
actor
}
class ActorWatcher extends Actor {
override def receive: Receive = {
case actorRef: ActorRef =>
context.watch(actorRef)
case Terminated(actorRef) =>
val key = actors.find(_._2 == actorRef).map(_._1)
key.foreach(actors.-=)
}
}
}
示例13: ExampleResponse
//设置package包名称以及导入依赖的类
package com.example.service
import akka.actor.ActorRefFactory
import org.apache.logging.log4j.LogManager
import spray.client.pipelining._
import spray.http.{FormData, HttpRequest, HttpResponse}
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol
import scala.concurrent.Future
case class ExampleResponse(id : String, name : String)
class ExampleClient(config : Configuration, implicit val system: ActorRefFactory) {
private object JsonProtocol extends DefaultJsonProtocol {
implicit val exampleResponseFormat = jsonFormat2(ExampleResponse)
}
import JsonProtocol._
import system.dispatcher
private val log = LogManager.getLogger(this.getClass)
private val logRequest: HttpRequest => HttpRequest = { r =>
log.debug(r.toString)
log.trace(r.entity.data.asString)
r
}
private val logResponse: HttpResponse => HttpResponse = { r =>
log.debug(r.toString)
log.trace(r.entity.data.asString)
r
}
private val jsonQuery = addHeader("Accept", "application/json") ~> logRequest ~> sendReceive ~> logResponse
def requestFuture(id : String) : Future[ExampleResponse] = {
val pipeline = jsonQuery ~> unmarshal[ExampleResponse]
pipeline {
Get(s"${config.ExampleRemoteServer.url}/getUser", FormData(Seq("id" -> id)))
}
}
}
示例14: FlexMappingModule
//设置package包名称以及导入依赖的类
package yang.flexmapping
import akka.actor.{ActorRef, ActorRefFactory, Props}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.{Bean, Configuration}
import yang.flexmapping.enrich.{Enrich, EnrichActor, EnrichSimpleImpl}
import yang.flexmapping.process.FlemxMappingProcesserCreator
@Configuration
class FlexMappingModule {
@Autowired
var actorFactory: ActorRefFactory = null
@Bean
def flexMappingProcessor: FlemxMappingProcesserCreator = new FlemxMappingProcesserCreator
@Autowired
var userManagerActor: ActorRef = null
@Bean
def flexMappingActor: ActorRef = {
actorFactory.actorOf(Props(new FlexMappingActor(flexMappingProcessor,userManagerActor)))
}
@Bean
def enrich:Enrich=new EnrichSimpleImpl
@Bean
def enrichActor:ActorRef={
actorFactory.actorOf(Props(new EnrichActor(enrich,flexMappingActor)))
}
}
示例15: GetExampleActor
//设置package包名称以及导入依赖的类
package com.app.service.example
import java.util.concurrent.atomic.AtomicInteger
import akka.actor.{ Actor, ActorLogging, ActorRefFactory, Props }
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.{ ActorMaterializer, ActorMaterializerSettings }
import akka.util.ByteString
import spray.json._
import spray.json.DefaultJsonProtocol
object GetExampleActor {
private val num = new AtomicInteger(0)
def name(str: String): String = s"$str-actor-${num.getAndIncrement()}"
def props(args: Any*) = Props(classOf[GetExampleActor], args)
def actorOf(args: Any*)(implicit ref: ActorRefFactory) =
ref.actorOf(props(args), name("GetExampleActor"))
}
class GetExampleActor
extends Actor with ActorLogging {
import akka.pattern.pipe
import context.dispatcher
final implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system))
val http = Http(context.system)
override def preStart() = {
http.singleRequest(HttpRequest(uri = "http://akka.io"))
.pipeTo(self)
}
def receive = {
case HttpResponse(StatusCodes.OK, headers, entity, _) ?
entity.dataBytes.runFold(ByteString(""))(_ ++ _).foreach { body ?
log.info("Got response, body: " + body.utf8String.parseJson.toString())
}
case resp @ HttpResponse(code, _, _, _) ?
log.info("Request failed, response code: " + code)
resp.discardEntityBytes()
}
}