本文整理汇总了Scala中scala.concurrent.ExecutionContextExecutor类的典型用法代码示例。如果您正苦于以下问题:Scala ExecutionContextExecutor类的具体用法?Scala ExecutionContextExecutor怎么用?Scala ExecutionContextExecutor使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ExecutionContextExecutor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Boot
//设置package包名称以及导入依赖的类
package com.dvisagie.vote
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.util.Timeout
import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.duration._
object Boot extends VoteService {
implicit val system = ActorSystem("user-system")
implicit val timeout: Timeout = Timeout(10.seconds)
implicit val executionContext: ExecutionContextExecutor = system.dispatcher
implicit val materializer = ActorMaterializer()
def main(args: Array[String]) {
val port = 5000
val bindingFuture = Http().bindAndHandle(routes, "0.0.0.0", port)
println(s"Server online at http://localhost:$port/")
// bindingFuture
// .onComplete(e => {
// println(s"Binding failure, terminating: ${e}")
// system.terminate()
// }) // and shutdown when done
}
}
示例2: executor
//设置package包名称以及导入依赖的类
package com.ferhtaydn.server
import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._
import akka.stream.Materializer
import com.ferhtaydn.models.{ JsonFormats, PatientInfo, PatientResult }
import com.ferhtaydn.rater.RatePredictor
import akka.http.scaladsl.model.StatusCodes._
import scala.concurrent.ExecutionContextExecutor
trait Server extends JsonFormats {
implicit val system: ActorSystem
implicit def executor: ExecutionContextExecutor
implicit val materializer: Materializer
val logger: LoggingAdapter
def predictor: RatePredictor
protected val routes: Route =
pathPrefix("cancerater") {
get {
pathSingleSlash {
complete("Welcome to CanceRater")
}
} ~
get {
path("cm") {
complete {
predictor.confusionMatrixString.map[ToResponseMarshallable] {
case cm ? cm
}
}
}
} ~
post {
path("check") {
entity(as[PatientInfo]) { patientInfo ?
complete {
predictor.predict(patientInfo).map[ToResponseMarshallable] {
case Right(score) ? PatientResult(score)
case Left(error) ? BadRequest ? error
}
}
}
}
}
}
}
示例3: RatePredictor
//设置package包名称以及导入依赖的类
package com.ferhtaydn.rater
import akka.actor.ActorSystem
import com.ferhtaydn.models.PatientInfo
import org.apache.spark.ml.feature.StringIndexerModel
import org.apache.spark.ml.tuning.CrossValidatorModel
import org.apache.spark.mllib.linalg.{ Matrix, Vector }
import org.apache.spark.sql.{ Row, SQLContext }
import scala.concurrent.{ ExecutionContextExecutor, Future }
class RatePredictor(system: ActorSystem, sqlContext: SQLContext,
indexModel: StringIndexerModel, cvModel: CrossValidatorModel,
confusionMatrix: String) {
private val decimalFormatter = new java.text.DecimalFormat("##.##")
private val blockingDispatcher: ExecutionContextExecutor = system.dispatchers.lookup("ml.predictor.dispatcher")
def confusionMatrixString: Future[String] = {
Future {
confusionMatrix
}(blockingDispatcher)
}
def predict(patientInfo: PatientInfo): Future[Either[String, Double]] = {
Future {
val df = sqlContext.createDataFrame(Seq(patientInfo.toRecord))
val indexedJobDF = indexModel.transform(df)
val result = cvModel
.transform(indexedJobDF)
.select("prediction", "probability").map {
case Row(prediction: Double, probability: Vector) ?
(probability, prediction)
}
result.collect().headOption match {
case Some((prob, _)) ? Right(decimalFormatter.format(prob(1)).toDouble)
case None ? Left(s"No result can be predicted for the patient")
}
}(blockingDispatcher)
}
}
示例4: WebServer
//设置package包名称以及导入依赖的类
package dummy_authenticator.server
import akka.actor.ActorSystem
import akka.http.scaladsl._
import akka.stream.ActorMaterializer
import dummy_authenticator.config.Configuration
import dummy_authenticator.rest.Routes
import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn
object WebServer extends Routes {
val config: Configuration = Configuration.get
implicit val system = ActorSystem(config.app.name)
implicit val materializer = ActorMaterializer()
implicit val ec: ExecutionContextExecutor = system.dispatcher
def main(args: Array[String]) {
val interface = config.server.interface
val port = config.server.dummy_port
// The Magic Words
val bindingFuture = Http().bindAndHandle(routes, interface, port)
// Console "Controls"
println(s"dummy_authenticator online at http://$interface:$port/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
// Closing Shop
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
}
示例5: WebServer
//设置package包名称以及导入依赖的类
package co.horn.alkes.server
import akka.actor.ActorSystem
import akka.http.scaladsl._
import akka.stream.ActorMaterializer
import co.horn.alkes.auth._
import co.horn.alkes.config.Configuration
import co.horn.alkes.dao.DataHandler
import co.horn.alkes.dao.implementations.riak.RiakDataHandler
import co.horn.alkes.log.Logger
import co.horn.alkes.rest.Routes
import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn
object WebServer extends Routes {
implicit val system = ActorSystem("alkes")
implicit val materializer = ActorMaterializer()
implicit val ec: ExecutionContextExecutor = system.dispatcher
val config: Configuration = Configuration.get
val dao: DataHandler = new RiakDataHandler(config)
val auth: Authority = new WasatAuthority(config)
val log: Logger = config.log.server
def main(args: Array[String]) {
val interface = config.server.interface
val port = config.server.port
// The Magic Words
val bindingFuture = Http().bindAndHandle(routes, interface, port)
// Console "Controls"
println(s"alkes online at http://$interface:$port/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
// Closing Shop
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
}
示例6: deleteBucket
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.s3v4
import akka.actor.ActorSystem
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import edu.goldlok.minio_scala.auth.MioKeys
import scala.concurrent.{ExecutionContextExecutor, Future}
def deleteBucket(bucket: String)
(implicit system: ActorSystem,
mater: ActorMaterializer,
dispatcher: ExecutionContextExecutor): Future[Boolean] = {
for {
result <- deleteBucketRaw(bucket)
} yield {
if (result.isSuccess) true
else {
if (result.ex.isDefined) throw result.ex.get
else throw new Throwable(s"minio server response status not ok! status: ${result.status}")
}
}
}
}
示例7: makeBucket
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.s3v4
import akka.actor.ActorSystem
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import edu.goldlok.minio_scala.auth.MioKeys
import scala.concurrent.{ExecutionContextExecutor, Future}
def makeBucket(bucket: String)
(implicit system: ActorSystem,
mater: ActorMaterializer,
dispatcher: ExecutionContextExecutor): Future[Boolean] = {
val response = this.makeBucketRaw(bucket)
for {
result <- response
} yield {
if (result.isSuccess) true
else {
if (result.ex.isDefined) throw result.ex.get
else throw new Throwable(s"minio server response status not ok! status: ${result.status}")
}
}
}
}
示例8: MioSystem
//设置package包名称以及导入依赖的类
package examples
import akka.actor.{ActorSystem, Terminated}
import akka.stream.ActorMaterializer
import edu.goldlok.minio_scala.auth.MioKeys
import edu.goldlok.minio_scala.mio.MioClient
import io.minio.MinioClient
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContextExecutor, Future}
object MioSystem {
implicit val mioSystem = ActorSystem("mio_system")
implicit val mater = ActorMaterializer()
implicit val dispatcher: ExecutionContextExecutor = mioSystem.dispatcher
implicit val keys = MioKeys("12345678", "12345678")
implicit val bucket = "guangzhou"
implicit val notfoundBucket = "guangzhou1"
implicit val timeout: FiniteDuration = 180.seconds
private val host = "192.168.2.245"
private val port = 9001
implicit val mc = MioClient(host, 9001, keys, blockSize = 5 * 1024 * 1024)
implicit val jmc = new MinioClient(s"http://$host:$port", "12345678", "12345678")
def stopSystem(): Future[Terminated] = mioSystem.terminate()
}
示例9: TestElem
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.s3v4
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import edu.goldlok.minio_scala.auth.MioKeys
import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.duration._
object TestElem {
val EXPECTED_EXCEPTION_DID_NOT_FIRE = "Expected exception did not fire"
val BUCKET = "bucket"
val OBJECT = "object"
val CONTENT_LENGTH = "Content-Length"
val APPLICATION_OCTET_STREAM = "application/octet-stream"
val APPLICATION_JAVASCRIPT = "application/javascript"
val CONTENT_TYPE = "Content-Type"
val MON_04_MAY_2015_07_58_51_GMT = "Mon, 04 May 2015 07:58:51 GMT"
val LAST_MODIFIED = "Last-Modified"
val HELLO_WORLD = "hello world"
val HELLO = "hello"
val BYTES = "bytes"
val ENC_KEY = "x-amz-meta-x-amz-key"
val ENC_IV = "x-amz-meta-x-amz-iv"
val MAT_DESC = "x-amz-meta-x-amz-matdesc"
val ACCEPT_RANGES = "Accept-Ranges"
val CONTENT_RANGE = "Content-Range"
val MON_29_JUN_2015_22_01_10_GMT = "Mon, 29 Jun 2015 22:01:10 GMT"
val BUCKET_KEY = "/bucket/key"
val MD5_HASH_STRING = "\"5eb63bbbe01eeed093cb22bb8f5acdc3\""
implicit val mioSystem = ActorSystem("mio_system")
implicit val mater = ActorMaterializer()
implicit val dispatcher: ExecutionContextExecutor = mioSystem.dispatcher
implicit val keys = MioKeys("", "")
val timeout: FiniteDuration = 180.seconds
}
示例10: HomeService
//设置package包名称以及导入依赖的类
package org.helianto.hackabase
import akka.actor.ActorSystem
import org.helianto.hackabase.domain.Project
import play.api.libs.json._
import play.api.mvc._
import play.api.routing.sird._
import scala.concurrent.ExecutionContextExecutor
object HomeService {
implicit val system: ActorSystem = ActorSystem("hackabase")
implicit def executor: ExecutionContextExecutor = system.dispatcher
val routes: PartialFunction[RequestHeader, Action[JsValue]] = {
case POST(p"/sendConfirmation") => Action(BodyParsers.parse.json) { request =>
request.body.validate[Project] match {
case s: JsSuccess[Project] =>
// TODO
Results.Ok(s"Successfuly sent!")
case e: JsError => Results.InternalServerError
}
}
}
}
示例11: Util
//设置package包名称以及导入依赖的类
package com.bisphone.cassandra
import com.bisphone.cassandra
import com.bisphone.util.{AsyncResult, Convertor, SimpleError, ValueExtractor}
import com.bisphone.std._
import scala.concurrent.ExecutionContextExecutor
object Util {
private val regex = {
val raw = """(.*):(\d*)"""
raw.r
}
implicit val tupleOfStringAndInt = Convertor[String, (String, Int)]("String => (String, Int)") {
case regex(host,port) => (host, port.toInt)
case x => throw new RuntimeException(s"Invalid String for 'host:port': '${x}'")
}
implicit val cassandraConsistencyLevel =
Convertor[String, cassandra.ConsistencyLevel]("String => cassandra.ConsistencyLevel") { value =>
cassandra.ConsistencyLevel.get(value) match {
case Some(rsl) => rsl
case None =>
val msg = s"Invalid value for cassandra-consistencylevel: ${value}. Valid values: ${cassandra.ConsistencyLevel.values.mkString(",")}"
throw new RuntimeException(msg)
}
}
def cassandraConfig[T <: ValueExtractor](extractor: T)(
implicit ex: ExecutionContextExecutor
): AsyncResult[SimpleError, cassandra.Config] = {
for {
seeds <- extractor.nelist[(String, Int)]("seeds")
keyspace <- extractor.required[String]("keyspace")
readCL <- extractor.required[cassandra.ConsistencyLevel]("read-consistency-level")
writeCL <- extractor.required[cassandra.ConsistencyLevel]("write-consistency-level")
} yield Config(seeds, keyspace, readCL, writeCL)
}
def cassandraConnection[T <: ValueExtractor](extractor: T)(
implicit ex: ExecutionContextExecutor
): AsyncResult[SimpleError, cassandra.Connection] = {
for {
config <- cassandraConfig(extractor)
conn = new cassandra.Connection(config)
} yield conn
}
}
示例12: AppReturningChunking
//设置package包名称以及导入依赖的类
package com.github.michalbogacz.http.streaming
import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.util.ByteString
import com.mongodb.reactivestreams.client.{MongoClients, MongoCollection}
import org.bson.Document
import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn
object AppReturningChunking extends Directives {
implicit val system = ActorSystem()
implicit val dispatcher: ExecutionContextExecutor = system.dispatcher
implicit val mat = ActorMaterializer()
def main(args: Array[String]): Unit = {
val mongoClient = MongoClients.create()
val coll = mongoClient.getDatabase("test").getCollection("resources")
val route =
path("resources") {
get {
complete(HttpEntity(ContentTypes.`application/json`, getData(coll)))
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
def getData(coll: MongoCollection[Document]): Source[ByteString, NotUsed] =
Source.fromPublisher(coll.find())
.map(_.toJson)
.map(ByteString(_))
.intersperse(ByteString("["), ByteString(","), ByteString("]"))
}
示例13: ApiReturningList
//设置package包名称以及导入依赖的类
package com.github.michalbogacz.http.streaming
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import com.mongodb.reactivestreams.client.{MongoClients, MongoCollection}
import org.bson.Document
import scala.concurrent.{ExecutionContextExecutor, Future}
import scala.io.StdIn
object ApiReturningList extends ServiceDirectives {
implicit val system = ActorSystem()
implicit val dispatcher: ExecutionContextExecutor = system.dispatcher
implicit val mat = ActorMaterializer()
def main(args: Array[String]): Unit = {
val mongoClient = MongoClients.create()
val coll = mongoClient.getDatabase("test").getCollection("resources")
val route =
path("resources") {
pageParams { pageParams =>
get {
complete(getData(coll, pageParams).map(HttpEntity(ContentTypes.`application/json`, _)))
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
def getData(coll: MongoCollection[Document], pageParams: PageParams): Future[String] =
Source.fromPublisher(coll.find().skip(pageParams.skip).limit(pageParams.limit))
.map(_.toJson)
.intersperse("[", ",", "]")
.runFold("")((acc, e) ? acc + e)
}
示例14: ExecutionContextScheduler
//设置package包名称以及导入依赖的类
package reactor.core.scala.scheduler
import java.util.concurrent.Executor
import reactor.core.Disposable
import reactor.core.scheduler.Scheduler.Worker
import reactor.core.scheduler.{Scheduler, Schedulers}
import scala.concurrent.{ExecutionContext, ExecutionContextExecutor, ExecutionContextExecutorService}
class ExecutionContextScheduler private(val scheduler: Scheduler) extends Scheduler {
override def schedule(task: Runnable): Disposable = {
val cancellation = scheduler.schedule(task)
new Disposable {
override def dispose(): Unit = cancellation.dispose()
}
}
override def createWorker(): Worker = scheduler.createWorker()
}
object ExecutionContextScheduler {
def apply(executionContext: ExecutionContext): ExecutionContextScheduler = {
executionContext match {
case eces: ExecutionContextExecutorService => new ExecutionContextScheduler(Schedulers.fromExecutorService(eces))
case ece: ExecutionContextExecutor => new ExecutionContextScheduler(Schedulers.fromExecutor(ece))
case _ => new ExecutionContextScheduler(Schedulers.fromExecutor(new Executor {
override def execute(command: Runnable): Unit = executionContext.execute(command)
}))
}
}
}
示例15: MessageMsgPackProcessorActor
//设置package包名称以及导入依赖的类
package com.ubirch.avatar.core.actor
import akka.actor.{Actor, ActorLogging, Props}
import akka.http.scaladsl.HttpExt
import akka.stream.Materializer
import com.ubirch.avatar.core.device.DeviceDataRawManager
import com.ubirch.avatar.core.msgpack.MsgPacker
import com.ubirch.util.json.MyJsonProtocol
import com.ubirch.util.model.JsonErrorResponse
import com.ubirch.util.mongo.connection.MongoUtil
import org.apache.commons.codec.binary.Hex
import scala.concurrent.ExecutionContextExecutor
class MessageMsgPackProcessorActor(implicit mongo: MongoUtil, httpClient: HttpExt, materializer: Materializer)
extends Actor
with MyJsonProtocol
with ActorLogging {
implicit val executionContext: ExecutionContextExecutor = context.dispatcher
private val validatorActor = context.system.actorOf(Props(new MessageValidatorActor()))
//private val validatorActor = context.system.actorSelection(ActorNames.MSG_VALIDATOR)
override def receive: Receive = {
case binData: Array[Byte] =>
val s = sender()
val hexVal = Hex.encodeHexString(binData)
log.info(s"got some MsgPack data: $hexVal")
try {
val (u, t) = MsgPacker.unpack(binData)
DeviceDataRawManager.create(did = u, vals = t, mpraw = binData) match {
case Some(drd) =>
validatorActor forward drd
case None =>
log.error("could not parse input msgpack data")
s ! JsonErrorResponse(errorType = "Validation Error", errorMessage = "Invalid Data")
}
}
catch {
case e: Exception =>
log.error("received invalid data", e)
sender ! JsonErrorResponse(errorType = "Invalid Data Error", errorMessage = "Incalid Dataformat")
}
case _ =>
log.error("received unknown message")
sender ! JsonErrorResponse(errorType = "Validation Error", errorMessage = "Invalid Input Data")
}
}