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

Scala Status类代码示例

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

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



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


示例2: AkkademyDb

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

import akka.actor.Actor
import akka.event.Logging
import akka.actor.Status
import scala.collection.mutable.HashMap

import com.akkademy.messages._

class AkkademyDb extends Actor {
    val map = new HashMap[String, Object]
    val log = Logging(context.system, this)

    override def receive = {
        case SetRequest(key, value) => {
            log.info("received SetRequest - key: {}  - value: {}", key, value)
            map.put(key, value)
            sender() ! Status.Success(key)
        }
        case SetIfNotExistsRequest(key, value) => {
            log.info("received SetIfNotExistsRequest - key: {}  - value: {}", key, value)
            if (!map.contains(key)) map.put(key, value)
            sender() ! Status.Success(key)
        }
        case GetRequest(key) => {
            log.info("received GetRequest - key {}", key)
            map.get(key) match {
                case Some(value) => sender() ! value
                case None => sender() ! Status.Failure (KeyNotFoundException(key))
            }
        }
        case DeleteRequest(key) => {
            log.info("received DeleteRequest - key {}", key)
            if (map.contains(key)) {
                map -= key
                sender() ! Status.Success(key)
            } else {
                sender() ! Status.Failure(KeyNotFoundException(key))
            }
        }
        case o => {
            log.info("received unknown message: {}", o);
            sender() ! Status.Failure (new ClassNotFoundException)
        }
    }
} 
开发者ID:miguelsaddress,项目名称:akkademy-db,代码行数:47,代码来源:AkkademyDb.scala


示例3: AkkademyDb

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

import akka.actor.{Actor, Status}
import akka.event.Logging

import scala.collection.mutable.HashMap



class AkkademyDb extends Actor{
  val map = new HashMap[String, Object]
  val log = Logging(context.system, this)

  override def receive = {
    case SetRequest(key, value) => {
      log.info(s"received SetRequest - key: {$key} value: {$value}")
      map.put(key,value)
    }
    case others => log.info(s"received unknown messages: {$others}")
  }

}

class ScalaPongActor extends Actor{
  override def receive: Receive = {
    case "ping" => sender() ! "pong"
    case _ => sender() ! Status.Failure(new Exception("unknow message"))
  }
} 
开发者ID:hanchenyi,项目名称:FirstAkkaProject,代码行数:30,代码来源:AkkademyDb.scala


示例4: AtuwaDb

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

import akka.actor.{Actor, Status}
import akka.actor.Actor.Receive
import akka.event.Logging
import org.atuwadb.messages.{GetRequest, InvalidMessageTypeException, KeyNotFoundException, SetRequest}

import scala.collection.mutable


class AtuwaDb extends Actor {
  val map = new mutable.HashMap[String, Object]
  val log = Logging(context.system, this)

  override def receive: Receive = {
    case SetRequest(key, value) => {
      log.info("Received SetRequest - key: {} value: {}", key, value)
      map.put(key, value)
      sender() ! Status.Success
    }
    case GetRequest(key) => {
      log.info("Received GetRequest - key: {}", key)
      val response: Option[Object] = map.get(key)
      response match {
        case Some(x) => sender() ! x
        case None => sender() ! Status.Failure(new KeyNotFoundException(key))
      }
    }
    case o => sender() ! Status.Failure(new InvalidMessageTypeException("Received an invalid message: " + o))
  }
} 
开发者ID:logtrace,项目名称:atuwadb,代码行数:32,代码来源:AtuwaDb.scala


示例5: Sink

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

import akka.actor.{ ActorRef, Props, Status }
import akka.{ Done, NotUsed }
import akka.stream.{ Graph, SinkShape, UniformFanOutShape }
import akka.stream.scaladsl.{ SinkQueueWithCancel, Sink => AkkaSink }
import org.reactivestreams.{ Publisher, Subscriber }

import scala.collection.immutable
import scala.collection.immutable.Seq
import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try


object Sink {
  def set[T]: AkkaSink[T, Future[immutable.Set[T]]] = {
    AkkaSink.fromGraph(new CollectionStage[T, immutable.Set[T]](immutable.Set.newBuilder[T]))
  }

  def sortedSet[T](implicit ordering: Ordering[T]): AkkaSink[T, Future[immutable.SortedSet[T]]] = {
    AkkaSink.fromGraph(new CollectionStage[T, immutable.SortedSet[T]](immutable.SortedSet.newBuilder[T]))
  }

  def map[K, V]: AkkaSink[(K, V), Future[immutable.Map[K, V]]] = {
    AkkaSink.fromGraph(new CollectionStage[(K, V), immutable.Map[K, V]](immutable.Map.newBuilder[K, V]))
  }

  def list[T]: AkkaSink[T, Future[List[T]]] = {
    AkkaSink.fromGraph(new CollectionStage[T, List[T]](List.newBuilder[T]))
  }

  // Akka's API
  def fromGraph[T, M](g: Graph[SinkShape[T], M]): AkkaSink[T, M] = AkkaSink.fromGraph(g)
  def fromSubscriber[T](subscriber: Subscriber[T]): AkkaSink[T, NotUsed] = AkkaSink.fromSubscriber(subscriber)
  def cancelled[T]: AkkaSink[T, NotUsed] = AkkaSink.cancelled
  def head[T]: AkkaSink[T, Future[T]] = AkkaSink.head
  def headOption[T]: AkkaSink[T, Future[Option[T]]] = AkkaSink.headOption
  def last[T]: AkkaSink[T, Future[T]] = AkkaSink.last[T]
  def lastOption[T]: AkkaSink[T, Future[Option[T]]] = AkkaSink.lastOption[T]
  def seq[T]: AkkaSink[T, Future[Seq[T]]] = AkkaSink.seq[T]
  def asPublisher[T](fanout: Boolean): AkkaSink[T, Publisher[T]] = AkkaSink.asPublisher[T](fanout)
  def ignore: AkkaSink[Any, Future[Done]] = AkkaSink.ignore
  def foreach[T](f: T => Unit): AkkaSink[T, Future[Done]] = AkkaSink.foreach[T](f)
  def combine[T, U](
    first: AkkaSink[U, _],
    second: AkkaSink[U, _],
    rest: AkkaSink[U, _]*)(strategy: Int ? Graph[UniformFanOutShape[T, U], NotUsed]): AkkaSink[T, NotUsed] =
    AkkaSink.combine[T, U](first, second, rest: _*)(strategy)
  def foreachParallel[T](parallelism: Int)(f: T ? Unit)(implicit ec: ExecutionContext): AkkaSink[T, Future[Done]] =
    AkkaSink.foreachParallel[T](parallelism)(f)
  def fold[U, T](zero: U)(f: (U, T) ? U): AkkaSink[T, Future[U]] = AkkaSink.fold[U, T](zero)(f)
  def reduce[T](f: (T, T) ? T): AkkaSink[T, Future[T]] = AkkaSink.reduce(f)
  def onComplete[T](callback: Try[Done] => Unit): AkkaSink[T, NotUsed] = AkkaSink.onComplete(callback)
  def actorRef[T](ref: ActorRef, onCompleteMessage: Any): AkkaSink[T, NotUsed] =
    AkkaSink.actorRef(ref, onCompleteMessage)
  def actorRefWithAck[T](ref: ActorRef, onInitMessage: Any, ackMessage: Any, onCompleteMessage: Any,
    onFailureMessage: (Throwable) ? Any = Status.Failure): AkkaSink[T, NotUsed] =
    AkkaSink.actorRefWithAck(ref, onInitMessage, ackMessage, onCompleteMessage, onFailureMessage)
  def actorSubscriber[T](props: Props): AkkaSink[T, ActorRef] = AkkaSink.actorSubscriber(props)
  def queue[T](): AkkaSink[T, SinkQueueWithCancel[T]] = AkkaSink.queue[T]()
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:62,代码来源:Sink.scala


示例6: NewsletterService

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

import akka.actor.{Actor, ActorLogging, Props, Status}
import akka.http.scaladsl.model.StatusCodes
import com.tpalanga.account.model.{User, UserId}
import com.tpalanga.testlib.test.client.impl.NewsletterServiceRestClient.NewsletterServiceRestClientFactory
import com.tpalanga.testlib.test.client.impl.{NewsletterServiceRestClient, Subscriber}
import com.tpalanga.testlib.test.client.{NoEntity, Response}
import com.tpalanga.testlib.test.config.RestServiceConfig

object NewsletterService {
  case class Subscribe(user: User)
  case class Unsubscribe(id: UserId)

  case class CreateResponse(response: Response[Subscriber])
  case class DeleteResponse(response: Response[NoEntity])

  def props(restServiceConfig: RestServiceConfig, clientFactory: NewsletterServiceRestClientFactory = NewsletterServiceRestClient.defaultFactory): Props =
    Props(new NewsletterService(restServiceConfig, clientFactory))
}

class NewsletterService(restServiceConfig: RestServiceConfig, clientFactory: NewsletterServiceRestClientFactory) extends Actor with ActorLogging {
  import NewsletterService._
  import akka.pattern.pipe
  import context.dispatcher

  override def receive: Receive = {
    case Subscribe(user) =>
      newClient().subscriberCreate(Subscriber(user.id, user.name, user.email)).map(CreateResponse) pipeTo self

    case Unsubscribe(userId) =>
      newClient().subscriberDelete(userId).map(DeleteResponse) pipeTo self

    case CreateResponse(response) if response.status == StatusCodes.Created =>
      log.info("Subscribed to newsletter")

    case CreateResponse(response) =>
      log.info(s"Unexpected response while subscribing to newsletter $response")

    case DeleteResponse(response) if response.status == StatusCodes.OK =>
      log.info("Unsubscribed from newsletter")

    case DeleteResponse(response) =>
      log.info("Unsubscribed from newsletter")

    case Status.Failure(th) =>
      log.error(th, "Error on newsletter request")
  }

  private def newClient() = clientFactory(restServiceConfig, context.system)
} 
开发者ID:tpalanga,项目名称:akka-http-microservice,代码行数:52,代码来源:NewsletterService.scala


示例7: respondWith

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

import akka.actor.{Status, Actor}
import akka.pattern.pipe

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try
import scala.util.control.NonFatal

package object actors {
  trait PacBioActor extends Actor {
    def respondWith(x: => Any): Unit = {
      sender ! Try(x).recover{ case NonFatal(e) => Status.Failure(e) }.get
    }

    def pipeWith(x: => Future[Any])(implicit ec: ExecutionContext): Unit = {
      pipe(x.recover{ case NonFatal(e) => Status.Failure(e) }) to sender
    }
  }
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:21,代码来源:package.scala


示例8: IncomingMessageHandler

//设置package包名称以及导入依赖的类
package korolev.akkahttp.util

import akka.NotUsed
import akka.actor.{Actor, ActorRef, ActorSystem, Props, Status}
import akka.stream.scaladsl.Sink

class IncomingMessageHandler(publish: String => Unit,
                             destroyHandler: () => Unit)
                            (implicit actorSystem: ActorSystem) {

  val asSink: Sink[String, NotUsed] =
    Sink.actorRef(incomingMessageHandlerActor, ConnectionClosed)

  private class IncomingMessageHandlerActor extends Actor {
    override def receive: Receive = {
      case message: String =>
        publish(message)

      case ConnectionClosed =>
        destroyHandler()

      case Status.Failure =>
        self ! ConnectionClosed
    }
  }

  private lazy val incomingMessageHandlerActor: ActorRef =
    actorSystem.actorOf(Props(new IncomingMessageHandlerActor))

  private object ConnectionClosed

} 
开发者ID:fomkin,项目名称:korolev,代码行数:33,代码来源:IncomingMessageHandler.scala


示例9: AkkademyDB

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

import com.akkademy.messages._
import akka.actor.{Props, ActorSystem, Status, Actor}
import akka.event.Logging
import scala.collection.mutable.HashMap

class AkkademyDB extends Actor
{
  val map = new HashMap[String,Object]
  val log = Logging(context.system, this)
  override def receive() = 
  {
    case SetRequest(key, value) =>
        log.info("Received SetRequest - key: {} value {}", key, value)
        map.put(key, value)
	sender() ! Status.Success
    case GetRequest(key) =>
	log.info("received GetRequest - key: {}", key)
	val response: Option[Object] = map.get(key)
	response match
		{
			case Some(x) => sender() ! x
			case None => sender() ! Status.Failure(new KeyNotFoundException(key))
		}
    case o => Status.Failure(new ClassNotFoundException)
  }
}

object Main extends App {
	val system = ActorSystem("akkademy")
	system.actorOf(Props[AkkademyDB], name = "akkademy-db")
} 
开发者ID:Edmond1983,项目名称:akkademydb-ch2,代码行数:34,代码来源:AkkademyDB.scala


示例10: UserState

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

import akka.actor.{ActorLogging, ActorRef, Status}
import akka.cluster.sharding.ShardRegion.HashCodeMessageExtractor
import akka.persistence.PersistentActor
import com.softwaremill.sandbox.application.UserActor.{CreateUser, UserCreated}
import [email protected]@

case class UserState(name: String)

class UserActor extends PersistentActor with ActorLogging {

  var userState: Option[UserState] = None

  override def receiveRecover: Receive = {
    case event: UserCreated => userState = Some(UserState(event.name))
  }
  override def receiveCommand: Receive = {
    case command: CreateUser =>
      val currentSender = sender()
      log.debug("creating used")
      Thread.sleep(2500)
      persist(UserCreated(command.name)) { e =>
        userState = Some(UserState(e.name))
        Thread.sleep(1500)
        log.debug("user created")
        currentSender ! Status.Success(e.name)
      }
  }
  override def persistenceId: String = s"UA-${self.path.name}"
}

trait UserCommand {
  def userId: String
}

object UserActor {
  case class CreateUser(userId: String, name: String) extends UserCommand
  case class UserCreated(name: String)

  trait UserRegionTag

  type UserRegion = ActorRef @@ UserRegionTag
}

class UserActorMessageExtractor extends HashCodeMessageExtractor(10) {

  override def entityId(message: Any): String = message match {
    case command: UserCommand => command.userId
  }
} 
开发者ID:aludwiko,项目名称:sandbox,代码行数:52,代码来源:UserActor.scala


示例11: StringReverse

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

import akka.actor.{Actor, Status}
import com.stringReverse.messages.{ReversibleString, ReversedString}
import akka.event.Logging

class StringReverse extends Actor{
  val log = Logging(context.system, this)

  override def receive = {
    case ReversibleString(passedString) =>
      log.info("Received String - {} , Returned String - {}", passedString, passedString.reverse)
      println(passedString.reverse)
      sender() ! passedString.reverse

    case o =>
      Status.Failure(new ClassNotFoundException)
      log.info("Unknown Message Received")
      sender() ! "ERROR: Unknown Message"
  }

} 
开发者ID:tcheuer,项目名称:LearningAkka-Chapter2General,代码行数:23,代码来源:stringReverse.scala


示例12: HttpApi

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

import java.net.InetSocketAddress

import akka.actor.{ Actor, ActorSystem, Status }
import akka.event.LoggingAdapter
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer

import scala.concurrent.{ ExecutionContext, Future }

abstract class HttpApi extends Actor {

  val log: LoggingAdapter
  val path = self.path

  val name: String

  val host: String
  val port: Int

  implicit val system: ActorSystem
  implicit val materializer: ActorMaterializer
  implicit val ec: ExecutionContext

  val paths: Route
  val http: Future[ServerBinding]

  override def preStart(): Unit = {
    super.preStart()
    log.info(s"Started $path")
  }

  override def postStop(): Unit = {
    super.postStop()
    log.info(s"Stopped $path")
  }

  override def receive: Receive = {
    case Http.ServerBinding(s) => handleServerBinding(s)
    case Status.Failure(e) => handleBindFailure(e)
  }

  private def handleServerBinding(address: InetSocketAddress): Unit = {
    log.info(s"$name started on {}", address)
    context.become(Actor.emptyBehavior)
  }

  private def handleBindFailure(error: Throwable): Unit = {
    log.error(s"Failed to bind to $host:$port")
    context stop self
  }

} 
开发者ID:jmarin,项目名称:akka-cluster-example,代码行数:57,代码来源:HttpApi.scala


示例13: AkkadmeyDB

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

import akka.actor.{Status, Actor}
import akka.actor.Actor.Receive
import akka.event.Logging
import com.harmeetsingh13.chapter2.messages.{KeyNotFoundException, GetRequest, SetRequest}

import scala.collection.mutable.HashMap


class AkkadmeyDB extends Actor{

  val map = new HashMap[String, Object]
  val log = Logging(context.system, this)

  override def receive: Receive = {
    case SetRequest(key, value) =>
      log.info("received SetRequest - key: {} value: {}", key, value)
      map.put(key, value)
      sender() ! Status.Success
    case GetRequest(key) =>
      log.info("received GetRequest - key: {}", key)
      val response = map.get(key)
      response match{
        case Some(x) => sender() ! x
        case None => Status.Failure(new KeyNotFoundException(key))
      }
    case o => Status.Failure(new ClassNotFoundException())
  }
} 
开发者ID:harmeetsingh0013,项目名称:Akka-practice-using-scala,代码行数:31,代码来源:AkkadmeyDB.scala


示例14: ScalaPongActor

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

import akka.actor.{Props, Status, Actor}
import akka.event.Logging


class ScalaPongActor extends Actor{

  val log = Logging(context.system, this)

  override def receive = {
    case "Ping" => {
      log.info("New message recived")
      sender() ! "Pong"
    }
    case _ => sender() ! Status.Failure(new Exception("unknow message"))
  }
}

object ScalaPongActor{
  def props(response: String): Props = {
    Props(classOf[ScalaPongActor], response)
  }
} 
开发者ID:harmeetsingh0013,项目名称:Akka-practice-using-scala,代码行数:25,代码来源:ScalaPongActor.scala


示例15: PersonRepoActor

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

import akka.actor.{Actor, DiagnosticActorLogging, Props, Status}
import dal.actors.PersonRepoActor.{CreatePerson, GetPersons, PersonCreated, RepoPersons}
import models.Person
import org.slf4j.MDC

class PersonRepoActor extends Actor with DiagnosticActorLogging {

  var currentPersonNr = 0L
  var persons: List[Person] = List.empty[Person]

  val printer = context.actorOf(PrintNewPersonActor.props, "printer")

  def receive = {
    case CreatePerson("mrerror", _) =>
      log.error("mrerror is a bad person, current persons {}", persons)
      sender() ! Status.Failure(new IllegalArgumentException("mrerror is not vaild"))

    case CreatePerson(name, age) =>
      val person = Person(newPersonNr(), name, age)
      MDC.put("pnr", String.valueOf(person.id))
      persons = person +: persons
      log.info("person persisted")
      sender() ! PersonCreated(person)
      printer ! RepoPersons(persons)

    case GetPersons =>
      sender() ! RepoPersons(persons)
  }

  def newPersonNr() = {
    currentPersonNr = currentPersonNr + 1
    currentPersonNr
  }
}

object PersonRepoActor {

  def props = Props(new PersonRepoActor)

  case class CreatePerson(name: String, age: Int)

  case class PersonCreated(person: Person)

  case object GetPersons

  case class RepoPersons(persons: List[Person])
} 
开发者ID:tobnee,项目名称:rp-demo,代码行数:50,代码来源:PersonRepoActor.scala


示例16: DistributedProcessingWorker

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

import aecor.distributedprocessing.DistributedProcessing._
import aecor.distributedprocessing.DistributedProcessingWorker.KeepRunning
import aecor.distributedprocessing.serialization.Message
import aecor.effect.Async
import aecor.effect.Async.ops._
import akka.actor.{ Actor, ActorLogging, Props, Status }
import akka.pattern._

private[aecor] object DistributedProcessingWorker {
  def props[F[_]: Async](processWithId: Int => Process[F]): Props =
    Props(new DistributedProcessingWorker[F](processWithId))

  final case class KeepRunning(workerId: Int) extends Message
}

private[aecor] class DistributedProcessingWorker[F[_]: Async](processFor: Int => Process[F])
    extends Actor
    with ActorLogging {
  import context.dispatcher

  case class ProcessStarted(process: RunningProcess[F])
  case object ProcessTerminated

  var killSwitch: Option[() => Unit] = None

  override def postStop: Unit =
    killSwitch.foreach(_.apply())

  def receive: Receive = {
    case KeepRunning(workerId) =>
      log.info("[{}] Starting process", workerId)
      processFor(workerId).run.unsafeRun.map(ProcessStarted) pipeTo self
      context.become {
        case ProcessStarted(RunningProcess(watchTermination, terminate)) =>
          log.info("[{}] Process started", workerId)
          killSwitch = Some(terminate)
          watchTermination.unsafeRun.map(_ => ProcessTerminated) pipeTo self
          context.become {
            case Status.Failure(e) =>
              log.error(e, "Process failed")
              throw e

            case ProcessTerminated =>
              throw new IllegalStateException("Process terminated")
          }
        case Status.Failure(e) =>
          log.error(e, "Process failed to start")
          throw e
        case KeepRunning(_) =>
      }
  }
} 
开发者ID:notxcain,项目名称:aecor,代码行数:55,代码来源:DistributedProcessingWorker.scala


示例17: AkkaDb

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

import akka.actor.{Actor, Status}
import akka.event.Logging
import com.akkadb.{GetRequest, KeyNotFoundException, SetRequest}

import scala.collection.mutable.HashMap

class AkkaDb extends Actor {
  val map = new HashMap[String, Object]
  val log = Logging(context.system, this)

  override def receive = {
    case SetRequest(key, value) =>
      log.info("received SetRequest - key: {} value: {}", key, value)
      map.put(key, value)
      sender() ! Status.Success
    case GetRequest(key) =>
      log.info("received GetRequest - key: {}", key)
      val response: Option[Object] = map.get(key)
      response match {
        case Some(x) => sender() ! x
        case None => sender() ! Status.Failure(new
            KeyNotFoundException(key))
      }
    case o => Status.Failure(new ClassNotFoundException)
  }
} 
开发者ID:oneraghavan,项目名称:akka-db,代码行数:29,代码来源:AkkaDb.scala


示例18: AkkademyDb

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

import akka.actor.{Actor, ActorLogging, ActorSystem, Props, Status}
import akka.event.LoggingReceive
import com.akkademy.messages._
import scala.collection.mutable.HashMap
import org.slf4j.LoggerFactory

class AkkademyDb extends Actor with ActorLogging {

  val map = new HashMap[String, Any]

  def receive = LoggingReceive {

    case msg: Get =>
      log.info("Rcvd Get(key: [{}])", msg.key)
      map.get(msg.key) match {
        case Some(value) => sender() ! value 
        case None        => sender() ! Status.Failure(KeyNotFound(msg.key))
      }

    case msg: Set =>
      log.info("Rcvd Set(key: [{}], value: [{}])", msg.key, msg.value)
      sender() ! map.put(msg.key, msg.value)

    case msg: SetIfNotExists =>
      log.info("Rcvd SetIfNotExists(key: [{}], value: [{}])", msg.key, msg.value)
      sender() ! map.getOrElseUpdate(msg.key, msg.value)

    case msg: Delete =>
      log.info("Rcvd Delete(key: [{}])", msg.key)
      map.remove(msg.key) match {
        case Some(value) => sender() ! value 
        case None        => sender() ! Status.Failure(KeyNotFound(msg.key))
      }

    case msg: Clear =>
      log.info("Rcvd Clear")
      map.clear 
      sender() ! Status.Success

    case _ => sender() ! Status.Failure(UnexpectedMessage())
  }
}

object Main extends App {

  val log = LoggerFactory.getLogger(Main.getClass)

  val system = ActorSystem("akkademydb-server")
  val actor = system.actorOf(Props[AkkademyDb], name = "akkademydb")

  log.info("Actor started; has path: [{}]", actor.path)
} 
开发者ID:bahadley,项目名称:learning-akka,代码行数:55,代码来源:AkkademyDb.scala


示例19: HttpServer

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

import akka.stream.ActorMaterializerSettings
import akka.actor.{Actor, ActorLogging, Status}

object HttpServer {
  val HttpDispatcher = "akka.http.dispatcher"
  object Stop
}

class HttpServer(port: Int, address: String, override val sslFile: String,
                 keypass: String, storepass: String) extends Actor with ActorLogging
  with SslSupport {
  import HttpServer._
  import akka.http.scaladsl.Http
  import akka.pattern.pipe
  import akka.http.scaladsl.server.RouteResult._
  import akka.http.scaladsl.server.RouteConcatenation._

  implicit val system = context.system
  implicit val ex = system.dispatchers.lookup(HttpDispatcher)
  implicit val mat = akka.stream.ActorMaterializer(
    ActorMaterializerSettings.create(system)
      .withDispatcher(HttpDispatcher))(system)

  Http().bindAndHandle(
    api.RestApi.route(system, mat), address, port,
    connectionContext = https(keypass, storepass)).pipeTo(self)

  override def receive = {
    case b: akka.http.scaladsl.Http.ServerBinding => serverBinding(b)
    case Status.Failure(c) => handleBindFailure(c)
  }

  def serverBinding(b: akka.http.scaladsl.Http.ServerBinding) = {
    log.info("Binding on {}",  b.localAddress)
    context become bound(b)
  }

  def handleBindFailure(cause: Throwable) = {
    log.error(cause, s"Can't bind to $address:$port!")
    (context stop self)
  }

  def bound(b: akka.http.scaladsl.Http.ServerBinding): Receive = {
    case HttpServer.Stop =>
      log.info("Unbound {}:{}", address, port)
      b.unbind().onComplete { _ =>  mat.shutdown }
  }
} 
开发者ID:haghard,项目名称:akka-cluster-console,代码行数:51,代码来源:HttpServer.scala


示例20: DummyActorDispatchersExample

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

import akka.actor.{Actor, Status}

import scala.concurrent.{ExecutionContext, Future}


class DummyActorDispatchersExample extends Actor{
    val blockingIoDispatcher: ExecutionContext = context.system.dispatchers.lookup("blocking-io-dispatcher")

    override def receive: Receive = {
        val s = "Hello"

        case _: String => {
            val future: Future[String] = Future {
                s + " future!"
            }(blockingIoDispatcher)
            future onSuccess {
                case msg => println(msg)
            }
            print("Message received")
        }
        Status.Success
    }
} 
开发者ID:dazito,项目名称:LearningAkkaScalaServer,代码行数:26,代码来源:DummyActorDispatcherExample.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala ProcessLogger类代码示例发布时间:2022-05-23
下一篇:
Scala RandomStringUtils类代码示例发布时间: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