• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala ActorRefFactory类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了ActorRefFactory类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
  }
} 
开发者ID:allansene,项目名称:spray-scala-akka-book-catalog,代码行数:35,代码来源:GoogleBooksClient.scala


示例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)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:33,代码来源:LeadershipModule.scala


示例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]
      )
  }
} 
开发者ID:peteslater-sky,项目名称:SprayWorkshop,代码行数:36,代码来源:RestClient.scala


示例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)
  }
} 
开发者ID:lifeway,项目名称:Chadash,代码行数:18,代码来源:ActorFactory.scala


示例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
      }
    }
  }

} 
开发者ID:indarium,项目名称:imageGenEval,代码行数:43,代码来源:EtagServiceSpec.scala


示例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")
    }
  }
} 
开发者ID:rafaelkyrdan,项目名称:nest-app,代码行数:30,代码来源:WebSocketWorker.scala


示例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)
  }
} 
开发者ID:PagerDuty,项目名称:scheduler,代码行数:53,代码来源:OrderingExecutor.scala


示例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
    }
  }
} 
开发者ID:PagerDuty,项目名称:scheduler,代码行数:44,代码来源:PartitionSupervisorSpec.scala


示例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!")
      }
    }
  }
} 
开发者ID:LeagueForHacker,项目名称:Rest-Server-Demo,代码行数:41,代码来源:MyServiceSpec.scala


示例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")
    }

  }
} 
开发者ID:bszwej,项目名称:akka-microservice,代码行数:40,代码来源:Microservice.scala


示例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
    }
  }
} 
开发者ID:provegard,项目名称:ncdbg,代码行数:33,代码来源:DefaultDomainFactory.scala


示例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.-=)
    }
  }
} 
开发者ID:provegard,项目名称:ncdbg,代码行数:44,代码来源:CapturingDomainFactory.scala


示例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)))
    }
  }
} 
开发者ID:mwang633,项目名称:example-service,代码行数:47,代码来源:ExampleClient.scala


示例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)))

  }

} 
开发者ID:wjingyao2008,项目名称:firsttry,代码行数:36,代码来源:FlexMappingModule.scala


示例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()
  }

} 
开发者ID:witZack,项目名称:scala-akka-skeleton,代码行数:52,代码来源:GetExampleActor.scala


示例16: BenchBase

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

import akka.actor.{ActorRefFactory, ActorSystem, Props}
import akka.testkit.{TestActorRef, TestProbe}
import com.github.mauricio.async.db.Configuration
import com.github.mauricio.async.db.mysql.MySQLConnection
import com.typesafe.config.ConfigFactory
import org.scalameter.api._
import org.scalameter.picklers.Implicits._

import scala.concurrent.duration._
import scala.language.postfixOps
import scala.concurrent.Await

class BenchBase extends Bench[Double] {
  lazy val executor = LocalExecutor(
    new Executor.Warmer.Default,
    Aggregator.min[Double],
    measurer)
  lazy val measurer = new Measurer.Default
  lazy val reporter = new LoggingReporter[Double]
  lazy val persistor = Persistor.None

  implicit val system = ActorSystem("changestream", ConfigFactory.load("test.conf"))
  implicit val ec = system.dispatcher
  val probe = TestProbe()
  val maker = (_: ActorRefFactory) => probe.ref

  val testConfig = ConfigFactory.load("test.conf")

  def getProbedActorOf[K](klass: Predef.Class[K], configPath: String = "changestream") =
    TestActorRef(Props(klass, maker, testConfig.getConfig(configPath)))

  protected val config = testConfig.getConfig("changestream.mysql")
  protected val mysqlConfig = new Configuration(
    config.getString("user"),
    config.getString("host"),
    config.getInt("port"),
    Some(config.getString("password"))
  )

  protected val connectionTimeout = config.getLong("timeout")
  protected val connection = new MySQLConnection(mysqlConfig)
  Await.result(connection.connect, connectionTimeout milliseconds)
  val result = connection.sendQuery("drop database if exists changestream_test")
    .flatMap(_ => connection.sendQuery("create database changestream_test"))
    .flatMap(_ => connection.sendQuery(s"""
                                          | CREATE TABLE changestream_test.users (
                                          |   `id` int(11) NOT NULL AUTO_INCREMENT,
                                          |   `username` varchar(32) DEFAULT NULL,
                                          |   `password` varchar(32) DEFAULT NULL,
                                          |   `login_count` int(11) NOT NULL DEFAULT '0',
                                          |   `bio` text DEFAULT NULL,
                                          |   PRIMARY KEY (`id`)
                                          | ) ENGINE=InnoDB
        """.stripMargin))
  Await.result(result, (connectionTimeout * 3) milliseconds)
} 
开发者ID:mavenlink,项目名称:changestream,代码行数:59,代码来源:BenchBase.scala


示例17: KafkaPublisher

//设置package包名称以及导入依赖的类
package nl.tradecloud.kafka

import java.util.concurrent.atomic.AtomicInteger

import akka.Done
import akka.actor.{ActorRefFactory, ActorSystem, Props, SupervisorStrategy}
import akka.kafka.ProducerSettings
import akka.pattern.BackoffSupervisor
import akka.stream.Materializer
import nl.tradecloud.kafka.command.Publish
import nl.tradecloud.kafka.config.KafkaConfig
import org.apache.kafka.common.serialization.{ByteArraySerializer, StringSerializer}

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future, Promise}

class KafkaPublisher(system: ActorSystem)(implicit mat: Materializer, context: ActorRefFactory) {
  import KafkaPublisher._

  implicit val dispatcher: ExecutionContext = system.dispatchers.lookup("dispatchers.kafka-dispatcher")

  val kafkaConfig = KafkaConfig(system.settings.config)

  private lazy val publisherId = KafkaClientIdSequenceNumber.getAndIncrement

  private def publisherSettings = {
    val keySerializer = new StringSerializer
    val valueSerializer = new ByteArraySerializer

    ProducerSettings(system, keySerializer, valueSerializer).withBootstrapServers(kafkaConfig.brokers)
  }

  private val publisherProps: Props = KafkaPublisherActor.props(kafkaConfig, publisherSettings)
  private val backoffPublisherProps: Props = BackoffSupervisor.propsWithSupervisorStrategy(
    publisherProps, s"KafkaPublisherActor$publisherId", 3.seconds,
    30.seconds, 1.0, SupervisorStrategy.stoppingStrategy
  )
  private val publishActor = context.actorOf(backoffPublisherProps, s"KafkaBackoffPublisher$publisherId")

  def publish(topic: String, msg: AnyRef): Future[Done] = {
    val completed: Promise[Done] = Promise()

    publishActor ! Publish(topic, msg, completed)

    completed.future
  }

}

object KafkaPublisher {
  private val KafkaClientIdSequenceNumber = new AtomicInteger(1)
} 
开发者ID:tradecloud,项目名称:kafka-akka-extension,代码行数:53,代码来源:KafkaPublisher.scala


示例18: RecommenderAmqpRpcClient

//设置package包名称以及导入依赖的类
package eu.shiftforward.adstax.recommender.api.rpc

import akka.actor.ActorRefFactory

import eu.shiftforward.adstax.recommender.api._
import eu.shiftforward.adstax.recommender.api.rpc.TypeDescriptors._
import eu.shiftforward.adstax.util.AmqpClient
import eu.shiftforward.adstax.util.rpc.AmqpRpcJsonClient
import eu.shiftforward.apso.config.LazyConfigFactory
import eu.shiftforward.adstax.config
import pureconfig.syntax._


class RecommenderAmqpRpcClient(val amqp: AmqpClient, val rpcConfig: config.RpcClient)
    extends RecommenderClient with AmqpRpcJsonClient {

  def getRecommendationForUser(userId: String, clientId: Option[String], siteId: Option[String]) =
    dispatchRequest(GetRecommendation(UserRecommendationQuery(userId, clientId, siteId))).map(_.recommendation)

  def getRecommendationForProduct(productId: String, clientId: Option[String], siteId: Option[String]) =
    dispatchRequest(GetRecommendation(ProductRecommendationQuery(productId, clientId, siteId))).map(_.recommendation)
}

object RecommenderAmqpRpcClient {

  def apply(amqp: AmqpClient, rpcConfig: config.RpcClient): RecommenderAmqpRpcClient =
    new RecommenderAmqpRpcClient(amqp, rpcConfig)

  def apply(
    amqpConfig: config.RabbitMQ = LazyConfigFactory.load.getConfig("adstax.sdk.recommender.rabbitmq").toOrThrow[config.RabbitMQ],
    rpcConfig: config.RpcClient = LazyConfigFactory.load.getConfig("adstax.sdk.recommender.rpc").toOrThrow[config.RpcClient])(
    implicit
    actorRefFactory: ActorRefFactory): RecommenderAmqpRpcClient = {

    new RecommenderAmqpRpcClient(new AmqpClient(amqpConfig, "adstax-recommender-sdk"), rpcConfig)
  }
} 
开发者ID:ShiftForward,项目名称:adstax-sdk-scala,代码行数:38,代码来源:RecommenderAmqpRpcClient.scala


示例19: ProductFeederAmqpRpcClient

//设置package包名称以及导入依赖的类
package eu.shiftforward.adstax.productfeeder.api.rpc

import akka.actor.ActorRefFactory
import pureconfig.syntax._

import eu.shiftforward.adstax.config
import eu.shiftforward.adstax.productfeeder.api._
import eu.shiftforward.adstax.productfeeder.api.rpc.TypeDescriptors._
import eu.shiftforward.adstax.util.AmqpClient
import eu.shiftforward.adstax.util.rpc.AmqpRpcJsonClient
import eu.shiftforward.apso.config.LazyConfigFactory


class ProductFeederAmqpRpcClient(val amqp: AmqpClient, val rpcConfig: config.RpcClient)
    extends ProductFeederClient with AmqpRpcJsonClient {

  def getProduct(clientId: String, siteId: String, productId: String) =
    dispatchRequest(GetProduct(ProductQuery(clientId, siteId, productId))).map(_.productResult)

  def updateProduct(clientId: String, siteId: String, productId: String, productAttributes: Map[String, Any]) =
    dispatchRequest(UpdateProduct(clientId, siteId, ProductItem(productId, productAttributes))).map(_ => true)

  def deleteProduct(clientId: String, siteId: String, productId: String) =
    dispatchRequest(DeleteProduct(clientId, siteId, productId)).map(_ => true)
}

object ProductFeederAmqpRpcClient {

  def apply(amqp: AmqpClient, rpcConfig: config.RpcClient): ProductFeederAmqpRpcClient =
    new ProductFeederAmqpRpcClient(amqp, rpcConfig)

  def apply(
    amqpConfig: config.RabbitMQ = LazyConfigFactory.load.getConfig("adstax.sdk.product-feeder.rabbitmq").toOrThrow[config.RabbitMQ],
    rpcConfig: config.RpcClient = LazyConfigFactory.load.getConfig("adstax.sdk.product-feeder.rpc").toOrThrow[config.RpcClient])(
    implicit
    actorRefFactory: ActorRefFactory): ProductFeederAmqpRpcClient = {

    new ProductFeederAmqpRpcClient(new AmqpClient(amqpConfig, "adstax-product-feeder-sdk"), rpcConfig)
  }
} 
开发者ID:ShiftForward,项目名称:adstax-sdk-scala,代码行数:41,代码来源:ProductFeederAmqpRpcClient.scala


示例20: ModelUser

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

import core._
import Roles._

import akka.actor.{Actor, ActorRefFactory, Props}
import java.util.UUID
import org.joda.time.DateTime
import scala.collection.immutable.Map

class ModelUser(val mode: Option[String]) extends Actor {
  // Dummy data for illustration purposes, in ascending order by date

  val RolesetViewer = Roleset("Viewer", List())
  val RolesetUser = Roleset("User", List(RoleModifyOwn, RoleDeleteOwn, RoleAddNew))
  val RolesetAdmin = Roleset("Admin", List(RoleViewAll, RoleModifyAll, RoleDeleteAll))

  val tableUser = List(
    User(UUID.randomUUID.toString, Some("Jim"), Some("jim"), Some("jim123"),
      List(RolesetViewer)),
    User(UUID.randomUUID.toString, Some("John"), Some("john"), Some("john123"),
      List(RolesetUser)),
    User(UUID.randomUUID.toString, Some("Fred"), Some("fred"), Some("fred123"),
      List(RolesetUser, RolesetAdmin))
  )

  def receive: Receive = process(tableUser)

  def process(tableUser: List[User]): Receive = {
    case Login(name, password) =>
      sender ! tableUser.find { user =>
        user.login == Option(name) && user.password == Option(password)
      }
    case GetEntity(uuid) =>
      sender ! tableUser.find(_.id == uuid.toString)
    case ListWithOffset(User, _, offset, limit) =>
      sender ! EntityList(tableUser.drop(offset).take(limit))
    case AddEntity(user: User, _*) =>
      val newTableUser = tableUser.filterNot(_.id == user.id)
        context.become(process(user +: newTableUser))
        sender ! user
    case DeleteEntity(id) =>
      val entity = tableUser.find(_.id == id)
        context.become(process(tableUser.filterNot(_.id == id)))
        sender ! entity
  }
}

object ModelUser {
  def name = "modelUser"
  def apply(mode: Option[String])(implicit factory: ActorRefFactory) =
    factory.actorOf(Props(new ModelUser(mode)), name)
} 
开发者ID:enpassant,项目名称:jeeves,代码行数:54,代码来源:ModelUser.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala RoundRobinPool类代码示例发布时间:2022-05-23
下一篇:
Scala MemoryStream类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap