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


Scala Props类代码示例

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


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

示例1: RegistryServiceActor

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

import java.util.UUID

import akka.actor.{Props, ActorRef, Actor}
import com.pacbio.common.actors.{PacBioActor, ActorRefFactoryProvider}
import com.pacbio.common.dependency.Singleton
import com.pacbio.secondary.smrtlink.models.{RegistryResourceUpdate, RegistryProxyRequest, RegistryResourceCreate}

// TODO(smcclellan): Add scaladoc

object RegistryServiceActor {
  case class GetResources(id: Option[String])
  case class GetResource(uuid: UUID)
  case class CreateResource(create: RegistryResourceCreate)
  case class UpdateResource(uuid: UUID, update: RegistryResourceUpdate)
  case class DeleteResource(uuid: UUID)
  case class ProxyRequest(uuid: UUID, req: RegistryProxyRequest)
}

class RegistryServiceActor(registryDao: RegistryDao) extends PacBioActor {
  import RegistryServiceActor._

  def receive: Receive = {
    case GetResources(id)             => respondWith(registryDao.getResources(id))
    case GetResource(uuid)            => respondWith(registryDao.getResource(uuid))
    case CreateResource(create)       => respondWith(registryDao.createResource(create))
    case UpdateResource(uuid, update) => respondWith(registryDao.updateResource(uuid, update))
    case DeleteResource(uuid)         => respondWith(registryDao.deleteResource(uuid))
    case ProxyRequest(uuid, req)      => respondWith(registryDao.proxyRequest(uuid, req))
  }
}

trait RegistryServiceActorRefProvider {
  this: RegistryDaoProvider with ActorRefFactoryProvider =>

  val registryServiceActorRef: Singleton[ActorRef] =
    Singleton(() => actorRefFactory().actorOf(Props(classOf[RegistryServiceActor], registryDao()), "RegistryServiceActor"))
}

trait RegistryServiceActorProvider {
  this: RegistryDaoProvider =>

  val registryServiceActor: Singleton[RegistryServiceActor] = Singleton(() => new RegistryServiceActor(registryDao()))
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:46,代码来源:RegistryServiceActor.scala

示例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)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:52,代码来源:PinnedActorSpec.scala

示例3: ConnectionActor

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

import java.util.UUID

import akka.actor.{Actor, Props}
import pl.mtomanski.fsmdemo.actors.ConnectionActor._
import pl.mtomanski.fsmdemo.domain.{Connection, Destination, Origin}

class ConnectionActor extends Actor {

  override def receive = {
    case FetchSoonestConnections(origin) =>
      println("Connection actor is fetching soonest connections")
      sender() ! getSoonestConnections(origin)
  }

  private def getSoonestConnections(origin: Origin) = {
    val soonestConnections = Seq(
      Connection("1", origin, destination1, departure1),
      Connection("2", origin, destination2, departure2)
    )
    SoonestConnectionsFromOrigin(soonestConnections)
  }
}

object ConnectionActor {

  def props(): Props = Props(new ConnectionActor)

  case class FetchSoonestConnections(origin: Origin)

  case class SoonestConnectionsFromOrigin(connections: Seq[Connection])

  // Mocked
  val destination1 = Destination(UUID.randomUUID().toString, "Wroclaw")
  val destination2 = Destination(UUID.randomUUID().toString, "Warsaw")
  val departure1 = "18:15"
  val departure2 = "18:30"
} 
开发者ID:michaltomanski,项目名称:fsm-demo,代码行数:40,代码来源:ConnectionActor.scala

示例4: ResolveArtifactsActor

//设置package包名称以及导入依赖的类
package mesosphere.marathon.upgrade

import java.net.URL

import akka.actor.Status.Failure
import akka.actor.{ Actor, Props }
import akka.pattern.pipe
import mesosphere.marathon.ResolveArtifactsCanceledException
import mesosphere.marathon.io.storage.StorageProvider
import mesosphere.marathon.io.{ CancelableDownload, PathFun }
import mesosphere.util.Logging

import scala.concurrent.Promise

private[this] class ResolveArtifactsActor(
  url2Path: Map[URL, String],
  promise: Promise[Boolean],
  storage: StorageProvider)
    extends Actor
    with PathFun
    with Logging {

  import mesosphere.marathon.upgrade.ResolveArtifactsActor.DownloadFinished

  // all downloads that have to be performed by this actor
  var downloads = url2Path.map { case (url, path) => new CancelableDownload(url, storage, path) }

  override def preStart(): Unit = {
    import context.dispatcher
    downloads.map(_.get.map(DownloadFinished) pipeTo self)
    if (url2Path.isEmpty) promise.success(true) // handle empty list
  }

  override def postStop(): Unit = {
    downloads.foreach(_.cancel()) // clean up not finished artifacts
  }

  override def receive: Receive = {
    case DownloadFinished(download) =>
      downloads = downloads.filter(_ != download)
      if (downloads.isEmpty) promise.success(true)
    case Failure(ex) =>
      log.warn("Can not resolve artifact", ex) // do not fail the promise!
    case DeploymentActor.Shutdown =>
      if (!promise.isCompleted)
        promise.tryFailure(new ResolveArtifactsCanceledException("Artifact Resolving has been cancelled"))
      context.stop(self)
  }
}

object ResolveArtifactsActor {
  def props(
    url2Path: Map[URL, String],
    promise: Promise[Boolean],
    storage: StorageProvider): Props = Props(new ResolveArtifactsActor(url2Path, promise, storage))

  case class DownloadFinished(download: CancelableDownload)
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:59,代码来源:ResolveArtifactsActor.scala

示例5: Application

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

import com.franklevering.ports.adapters.http.HttpAdapter
import akka.actor.{ActorSystem, Props}
import akka.stream.ActorMaterializer
import com.franklevering.banking.domain.model.account.AccountRepository
import com.franklevering.banking.infrastructure.dependencyinjection.extension.GuiceAkkaExtension
import com.franklevering.banking.infrastructure.dependencyinjection.modules.{AkkaModule, InfrastructureModule, JournalModule}
import com.franklevering.ports.adapters.journal.{CassandraJournal, EngageStreaming}
import com.google.inject.Guice
import net.codingwell.scalaguice.InjectorExtensions._

object Application {
  def main(args: Array[String]): Unit = {
    val injector = Guice.createInjector(
      new AkkaModule(),
      new InfrastructureModule(),
      new JournalModule()
    )

    implicit  val system = injector.instance[ActorSystem]
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher
    system.actorOf(Props(classOf[CassandraJournal], injector.instance[AccountRepository])) ! EngageStreaming()
    HttpAdapter.startServer
  }
} 
开发者ID:frankieleef,项目名称:banking,代码行数:28,代码来源:Application.scala

示例6: ClientActor

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

import scala.reflect.ClassTag

import akka.actor.SupervisorStrategy.Stop
import akka.actor.{Actor, OneForOneStrategy, Props, Terminated}
import fs2.Task
import fs2.async.mutable.{Queue, Signal}

private class ClientActor[Out](props: Props, outQueue: Queue[Task, Out], closeSignal: Signal[Task, Boolean])
                              (implicit messageType: ClassTag[Out]) extends Actor {
  val serverActor = context actorOf props
  context watch serverActor
  
  def receive: Receive = {
    case Terminated(`serverActor`) =>
      closeSignal.set(true).unsafeRun()
      context stop self
    case messageType(m) if sender() == serverActor =>
      outQueue.enqueue1(m).unsafeRun()
    case m if sender() == serverActor =>
      org.log4s.getLogger.error(s"Server sent unhandled message ${m.getClass.getSimpleName} " +
        s"expecting a ${messageType.runtimeClass.getSimpleName}!")
    case m if sender() == self =>
      serverActor ! m
  }
  
  override def supervisorStrategy: OneForOneStrategy = OneForOneStrategy() {
    case _ => Stop
  }
} 
开发者ID:Lasering,项目名称:http4s-akka,代码行数:32,代码来源:ClientActor.scala

示例7: SDKMain

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

import akka.actor.{ActorSystem, Props}
import common.Tool._
import db.BackList


object SDKMain {
  def main(args: Array[String]) {
    UserApi.updateUsers
    run(Task.runTasks())
    //??????Actor
    val system = ActorSystem.create("PaiPai")
    val userActor = system.actorOf(Props[UserActor], name = "user_actor")
    val loanActor = system.actorOf(Props(new LoanActor(userActor)), name = "loan_actor")
    LoansApi.loanActor(loanActor)
  }

} 
开发者ID:livehl,项目名称:paipai,代码行数:20,代码来源:SDKMain.scala

示例8: RouteeCreationSpec

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

import akka.testkit.AkkaSpec
import akka.actor.Props
import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.LocalActorRef
import scala.concurrent.duration._
import akka.actor.Identify
import akka.actor.ActorIdentity

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class RouteeCreationSpec extends AkkaSpec {

  "Creating Routees" must {

    "result in visible routees" in {
      val N = 100
      system.actorOf(RoundRobinPool(N).props(Props(new Actor {
        system.actorSelection(self.path).tell(Identify(self.path), testActor)
        def receive = Actor.emptyBehavior
      })))
      for (i ? 1 to N) {
        expectMsgType[ActorIdentity] match {
          case ActorIdentity(_, Some(_)) ? // fine
          case x                         ? fail(s"routee $i was not found $x")
        }
      }
    }

    "allow sending to context.parent" in {
      val N = 100
      system.actorOf(RoundRobinPool(N).props(Props(new Actor {
        context.parent ! "one"
        def receive = {
          case "one" ? testActor forward "two"
        }
      })))
      val gotit = receiveWhile(messages = N) {
        case "two" ? lastSender.toString
      }
      expectNoMsg(100.millis)
      if (gotit.size != N) {
        fail(s"got only ${gotit.size} from [${gotit mkString ", "}]")
      }
    }

  }

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

示例9: AddressTerminatedTopicBenchSpec

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

import scala.concurrent.duration._
import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Address
import akka.actor.Props
import akka.testkit._

object AddressTerminatedTopicBenchSpec {

  class Subscriber(testActor: ActorRef) extends Actor {
    AddressTerminatedTopic(context.system).subscribe(self)
    testActor ! "started"

    override def postStop(): Unit = {
      AddressTerminatedTopic(context.system).unsubscribe(self)
    }

    def receive = Actor.emptyBehavior
  }
}

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class AddressTerminatedTopicBenchSpec extends AkkaSpec("akka.loglevel=INFO") {
  import AddressTerminatedTopicBenchSpec._

  "Subscribe and unsubscribe of AddressTerminated" must {

    "be quick" in {
      val sys = ActorSystem(system.name + "2", system.settings.config)
      try {
        val num = 20000

        val t1 = System.nanoTime()
        val p = Props(classOf[Subscriber], testActor)
        val subscribers = Vector.fill(num)(sys.actorOf(p))
        receiveN(num, 10.seconds)
        log.info("Starting {} actors took {} ms", num, (System.nanoTime() - t1).nanos.toMillis)

        val t2 = System.nanoTime()
        shutdown(sys, 10.seconds, verifySystemShutdown = true)
        log.info("Stopping {} actors took {} ms", num, (System.nanoTime() - t2).nanos.toMillis)
      } finally {
        if (!sys.isTerminated) shutdown(sys)
      }
    }

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

示例10: LookupApplication

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

import scala.concurrent.duration._
import scala.util.Random
import com.typesafe.config.ConfigFactory
import akka.actor.ActorSystem
import akka.actor.Props

object LookupApplication {
  def main(args: Array[String]): Unit = {
    if (args.isEmpty || args.head == "Calculator")
      startRemoteCalculatorSystem()
    if (args.isEmpty || args.head == "Lookup")
      startRemoteLookupSystem()
  }

  def startRemoteCalculatorSystem(): Unit = {
    val system = ActorSystem("CalculatorSystem",
      ConfigFactory.load("calculator"))
    system.actorOf(Props[CalculatorActor], "calculator")

    println("Started CalculatorSystem - waiting for messages")
  }

  def startRemoteLookupSystem(): Unit = {
    val system =
      ActorSystem("LookupSystem", ConfigFactory.load("remotelookup"))
    val remotePath =
      "akka.tcp://[email protected]:2552/user/calculator"
    val actor = system.actorOf(Props(classOf[LookupActor], remotePath), "lookupActor")

    println("Started LookupSystem")
    import system.dispatcher
    system.scheduler.schedule(1.second, 1.second) {
      if (Random.nextInt(100) % 2 == 0)
        actor ! Add(Random.nextInt(100), Random.nextInt(100))
      else
        actor ! Subtract(Random.nextInt(100), Random.nextInt(100))
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:42,代码来源:LookupApplication.scala

示例11: CreationApplication

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

import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory
import scala.util.Random
import akka.actor.ActorSystem
import akka.actor.Props

object CreationApplication {
  def main(args: Array[String]): Unit = {
    if (args.isEmpty || args.head == "CalculatorWorker")
      startRemoteWorkerSystem()
    if (args.isEmpty || args.head == "Creation")
      startRemoteCreationSystem()
  }

  def startRemoteWorkerSystem(): Unit = {
    ActorSystem("CalculatorWorkerSystem", ConfigFactory.load("calculator"))
    println("Started CalculatorWorkerSystem")
  }

  def startRemoteCreationSystem(): Unit = {
    val system =
      ActorSystem("CreationSystem", ConfigFactory.load("remotecreation"))
    val actor = system.actorOf(Props[CreationActor],
      name = "creationActor")

    println("Started CreationSystem")
    import system.dispatcher
    system.scheduler.schedule(1.second, 1.second) {
      if (Random.nextInt(100) % 2 == 0)
        actor ! Multiply(Random.nextInt(20), Random.nextInt(20))
      else
        actor ! Divide(Random.nextInt(10000), (Random.nextInt(99) + 1))
    }

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

示例12: HelloWorld

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

import akka.actor.Actor
import akka.actor.Props

class HelloWorld extends Actor {

  override def preStart(): Unit = {
    // create the greeter actor
    val greeter = context.actorOf(Props[Greeter], "greeter")
    // tell it to perform the greeting
    greeter ! Greeter.Greet
  }

  def receive = {
    // when the greeter is done, stop this actor and with it the application
    case Greeter.Done => context.stop(self)
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:20,代码来源:HelloWorld.scala

示例13: LogSourceSpec

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

import scala.concurrent.duration._
import akka.testkit.AkkaSpec
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.Props
import akka.event.Logging
import akka.testkit.ImplicitSender
import akka.testkit.TestProbe
import akka.actor.Deploy
import akka.event.Logging.Info
import akka.actor.ExtendedActorSystem

object LogSourceSpec {
  class Reporter extends Actor with ActorLogging {
    def receive = {
      case s: String ?
        log.info(s)
    }
  }
}

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class LogSourceSpec extends AkkaSpec(
  """
    akka.loglevel = INFO
    akka.actor.provider = "akka.remote.RemoteActorRefProvider"
    akka.remote.netty.tcp.port = 0
  """) {

  import LogSourceSpec._

  val reporter = system.actorOf(Props[Reporter], "reporter")
  val logProbe = TestProbe()
  system.eventStream.subscribe(system.actorOf(Props(new Actor {
    def receive = {
      case i @ Info(_, _, msg: String) if msg contains "hello" ? logProbe.ref ! i
      case _ ?
    }
  }).withDeploy(Deploy.local), "logSniffer"), classOf[Logging.Info])

  "Log events" must {

    "should include host and port for local LogSource" in {
      reporter ! "hello"
      val info = logProbe.expectMsgType[Info]
      info.message should be("hello")
      val defaultAddress = system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress
      info.logSource should include(defaultAddress.toString)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:54,代码来源:LogSourceSpec.scala

示例14: MySpec

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

//#plain-spec
import akka.actor.ActorSystem
import akka.actor.Actor
import akka.actor.Props
import akka.testkit.{ TestActors, TestKit, ImplicitSender }
import org.scalatest.WordSpecLike
import org.scalatest.Matchers
import org.scalatest.BeforeAndAfterAll

//#implicit-sender
class MySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {
  //#implicit-sender

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "An Echo actor" must {

    "send back messages unchanged" in {
      val echo = system.actorOf(TestActors.echoActorProps)
      echo ! "hello world"
      expectMsg("hello world")
    }

  }
}
//#plain-spec 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:34,代码来源:PlainWordSpec.scala

示例15: MormontShardRegion

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

import akka.actor.{ActorRef, ActorSystem, Props}
import akka.cluster.sharding.{ClusterSharding, ClusterShardingSettings, ShardRegion}
import lib.MormontConfig
import lib.cluster.MormontShardRegion.MormontShardRegionActorRef
import lib.models.PayLoad


abstract class MormontShardRegion[T <: PayLoad](actorSystem: ActorSystem) {
  private val prefix : String = "shard-region-"
  def channelName: String

  def entityProps: Props

  final private val extractEntityId: ShardRegion.ExtractEntityId = {
    case p: PayLoad ?
      (p.persistenceId, p)
  }

  final private val extractShardId: ShardRegion.ExtractShardId = {
    case p: PayLoad ?
      (math.abs(p.persistenceId.hashCode) % MormontConfig.numOfShards).toString
  }

  final def startShard(): MormontShardRegionActorRef = {
   ClusterSharding(actorSystem).start(
      typeName = prefix + channelName,
      entityProps = entityProps,
      settings = ClusterShardingSettings(actorSystem),
      extractEntityId = extractEntityId,
      extractShardId = extractShardId
    )
  }
}

object MormontShardRegion {
  type MormontShardRegionActorRef = ActorRef
} 
开发者ID:sharma-rohit,项目名称:mormont,代码行数:40,代码来源:MormontShardRegion.scala


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