本文整理汇总了Scala中scala.concurrent.ExecutionContext类的典型用法代码示例。如果您正苦于以下问题:Scala ExecutionContext类的具体用法?Scala ExecutionContext怎么用?Scala ExecutionContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ExecutionContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: CassandraSink
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.cassandra.scaladsl
import akka.Done
import akka.stream.scaladsl.{Flow, Keep, Sink}
import com.datastax.driver.core.{BoundStatement, PreparedStatement, Session}
import scala.concurrent.{ExecutionContext, Future}
import akka.stream.alpakka.cassandra.GuavaFutures._
object CassandraSink {
def apply[T](
parallelism: Int,
statement: PreparedStatement,
statementBinder: (T, PreparedStatement) => BoundStatement
)(implicit session: Session, ex: ExecutionContext): Sink[T, Future[Done]] =
Flow[T]
.mapAsyncUnordered(parallelism)(t ? session.executeAsync(statementBinder(t, statement)).asScala())
.toMat(Sink.ignore)(Keep.right)
}
开发者ID:akka,项目名称:alpakka,代码行数:21,代码来源:CassandraSink.scala
示例2: add
//设置package包名称以及导入依赖的类
package services
import com.google.inject.{ImplementedBy, Inject}
import model.{Artist, ArtistDAO, Temp}
import play.api.libs.json.{JsValue, Json, Writes}
import play.api.Logger
import scala.concurrent.ExecutionContext
@ImplementedBy(classOf[ArtistServicesImpl])
trait ArtistServices {
def add (discActor : Artist) : Boolean
def findAllByType(value: String) : ArtistResponse
}
case class ArtistResponse(artists : List[Artist])
object ArtistResponse {
//implicit val formatter1 = Json.format[Artist]
implicit val formatter2 = Json.format[ArtistResponse]
Logger.debug("Attempting risky calculation.")
implicit val implicitFooWrites = new Writes[ArtistResponse] {
def writes(discActors : ArtistResponse): JsValue = {
Json.obj(
"artists" -> discActors.artists
)
}
}
}
class ArtistServicesImpl @Inject()(dao: ArtistDAO )(implicit ec: ExecutionContext) extends ArtistServices {
override def add(artist : Artist ): Boolean = {
if(dao.addNew(artist)!=null)
true
else
false
}
override def findAllByType(value: String): ArtistResponse = {
println("Find Artist by Name: " + value)
ArtistResponse(dao.getAllByName(value).filter(a => a.isDefined).map(a => a.get))
}
}
开发者ID:ralekar,项目名称:play-scala-casbah,代码行数:47,代码来源:ArtistServices.scala
示例3: ExampleFilter
//设置package包名称以及导入依赖的类
package filters
import akka.stream.Materializer
import javax.inject._
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class ExampleFilter @Inject()(
implicit override val mat: Materializer,
exec: ExecutionContext) extends Filter {
override def apply(nextFilter: RequestHeader => Future[Result])
(requestHeader: RequestHeader): Future[Result] = {
// Run the next filter in the chain. This will call other filters
// and eventually call the action. Take the result and modify it
// by adding a new header.
nextFilter(requestHeader).map { result =>
result.withHeaders("X-ExampleFilter" -> "foo")
}
}
}
开发者ID:fandfisf,项目名称:chicago-cycles,代码行数:25,代码来源:ExampleFilter.scala
示例4: AuthServiceRoute
//设置package包名称以及导入依赖的类
package com.noedominguez.class_orchestration.restapi.http.routes
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import com.noedominguez.class_orchestration.restapi.models.UserEntity
import com.noedominguez.class_orchestration.restapi.services.AuthService
import com.noedominguez.class_orchestration.restapi.http.SecurityDirectives
import de.heikoseeberger.akkahttpcirce.CirceSupport
import io.circe.generic.auto._
import io.circe.syntax._
import scala.concurrent.ExecutionContext
class AuthServiceRoute(val authService: AuthService)(implicit executionContext: ExecutionContext) extends CirceSupport with SecurityDirectives {
import StatusCodes._
import authService._
val route = pathPrefix("auth") {
path("signIn") {
pathEndOrSingleSlash {
post {
entity(as[LoginPassword]) { loginPassword =>
complete(signIn(loginPassword.login, loginPassword.password).map(_.asJson))
}
}
}
} ~
path("signUp") {
pathEndOrSingleSlash {
post {
entity(as[UserEntity]) { userEntity =>
complete(Created -> signUp(userEntity).map(_.asJson))
}
}
}
}
}
private case class LoginPassword(login: String, password: String)
}
开发者ID:poguez,项目名称:class_orchestration_api,代码行数:42,代码来源:AuthServiceRoute.scala
示例5: extractBearerToken
//设置package包名称以及导入依赖的类
package com.github.cupenya.microservices.sdk.authentication
import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directive1, Directives}
import com.github.cupenya.microservices.sdk.logging.Logging
import scala.concurrent.ExecutionContext
trait AuthorizationDirectives extends Logging {
self: Directives =>
implicit val ec: ExecutionContext
// TODO: dep injection
private val tokenVerifier = new JwtTokenVerifier
private def extractBearerToken(authHeader: Option[Authorization]): Option[String] =
authHeader.collect {
case Authorization(OAuth2BearerToken(token)) => token
}
def authorized: Directive1[AuthInfo] = {
optionalHeaderValueByType(classOf[Authorization]).map(extractBearerToken).flatMap {
case Some(token) =>
onComplete(tokenVerifier.verifyToken(token)).flatMap { x =>
x.map(authInfo => provide(authInfo))
.recover {
case ex =>
log.error("Couldn't log in using provided authorization token", ex)
reject(AuthorizationFailedRejection).toDirective[Tuple1[AuthInfo]]
}
.get
}
case None =>
reject(AuthorizationFailedRejection)
}
}
}
开发者ID:cupenya,项目名称:microservices-sdk,代码行数:39,代码来源:AuthorizationDirectives.scala
示例6: StoryServiceImpl
//设置package包名称以及导入依赖的类
package io.soheila.cms.services.stories
import io.soheila.cms.daos.StoryDAO
import io.soheila.cms.entities.{ Media, Story, UserReference }
import io.soheila.cms.services.exceptions.CMSServiceException
import io.soheila.cms.types.StoryType
import scala.concurrent.{ ExecutionContext, Future }
class StoryServiceImpl(val storyDAO: StoryDAO) extends StoryService {
override def read(uuid: String)(implicit ec: ExecutionContext): Future[Option[Story]] = {
storyDAO.findByUUID(uuid).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => s
}
}
override def initialize(uuid: String, storyType: StoryType.Value, userOption: Option[UserReference])(implicit ec: ExecutionContext): Future[Option[Story]] = {
storyDAO.create(uuid, Story(storyType, userOption)).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => Some(s)
}
}
override def findByTypeAndSlug(storyType: StoryType.Value, slug: String)(implicit ec: ExecutionContext): Future[Option[Story]] = {
storyDAO.findByTypeAndSlug(storyType, slug).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(story) => story
}
}
override def findAndUpdateLatest(story: Story, upsert: Boolean)(implicit ec: ExecutionContext): Future[Option[Story]] = {
storyDAO.findAndUpdateLatest(story, upsert).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => s
}
}
override def editMedia(uuid: String, medias: Set[Media])(implicit ec: ExecutionContext): Future[Boolean] = {
storyDAO.editMedia(uuid, medias).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => s
}
}
override def delete(uuid: String)(implicit ec: ExecutionContext): Future[Boolean] = {
storyDAO.delete(uuid).map {
case Left(dAOException) => throw CMSServiceException(dAOException.message, dAOException)
case Right(s) => true
}
}
}
开发者ID:esfand-r,项目名称:soheila-cm,代码行数:54,代码来源:StoryServiceImpl.scala
示例7: withMongoURL
//设置package包名称以及导入依赖的类
package io.scalajs.npm.mongoose
import io.scalajs.nodejs.process
import io.scalajs.npm.mongodb.{Db, MongoClient}
import org.scalatest.FunSpec
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
trait MongoDBTestSupport {
self: FunSpec =>
def withMongoURL[S](block: String => S): Any = {
process.env.get("MONGO_CONNECT") match {
case Some(url) => block(url)
case None =>
info("No MongoDB configuration. Set 'MONGO_CONNECT' (ex. MONGO_CONNECT=mongodb://localhost:27017/test)")
}
}
def withMongo[S](label: String)(block: Db => Future[S])(implicit ec: ExecutionContext): Any = {
process.env.get("MONGO_CONNECT") match {
case None =>
info("No MongoDB configuration. Set 'MONGO_CONNECT' (ex. MONGO_CONNECT=mongodb://localhost:27017/test)")
case Some(url) =>
val outcome = for {
db <- MongoClient.connectFuture(url)
result <- block(db)
} yield (db, result)
outcome onComplete {
case Success((db, _)) =>
info(s"$label: Closing connection....")
db.close()
case Failure(e) =>
throw new IllegalStateException(s"MongoDB connection failure: ${e.getMessage}")
}
}
}
}
开发者ID:scalajs-io,项目名称:mongoose,代码行数:44,代码来源:MongoDBTestSupport.scala
示例8: MainAppActor
//设置package包名称以及导入依赖的类
package com.github.unknownnpc.remotedebugtool.actor
import akka.actor.{Actor, ActorLogging, ActorRef, ActorSystem}
import com.github.unknownnpc.remotedebugtool.message._
import scala.concurrent.ExecutionContext
class MainAppActor()(implicit actorSystem: ActorSystem) extends Actor with ActorLogging {
private implicit val dispatcher: ExecutionContext = actorSystem.dispatcher
private var jdiVmServiceActor: ActorRef = _
private var reportServiceActor: ActorRef = _
override def preStart(): Unit = {
log.info("Main app actor starts")
reportServiceActor = createReportServiceActor()
jdiVmServiceActor = createJdiVmServiceActor()
}
override def postStop() {
log.info("Main app actor stops")
}
override def receive: Receive = {
case MainAppActorStart =>
startServices()
case MainAppActorStop =>
stopServices()
context.stop(self)
context.system.terminate()
}
private def startServices() = {
jdiVmServiceActor ! JdiVmServiceStart
}
private def stopServices() = {
log.info("Received command to stop all services")
jdiVmServiceActor ! JdiVmServiceStop
reportServiceActor ! ReportServiceStop
}
private def createJdiVmServiceActor() = {
context.actorOf(JdiVmServiceActor.props(reportServiceActor), "jdi-vm-service")
}
private def createReportServiceActor() = {
context.actorOf(ReportServiceActor.props(self), "report-service")
}
}
开发者ID:UnknownNPC,项目名称:remote-debug-tool,代码行数:56,代码来源:MainAppActor.scala
示例9: PaginatedResponseRetriever
//设置package包名称以及导入依赖的类
package com.dwolla.awssdk.utils
import com.dwolla.awssdk.utils.ScalaAsyncHandler.Implicits._
import scala.concurrent.{ExecutionContext, Future}
import scala.language.reflectiveCalls
import scala.reflect.ClassTag
object PaginatedResponseRetriever {
class PaginatedResponseRetriever[Req <: PaginatedRequest, Res <: PaginatedResult](requestFactory: () ? Req) {
def via(awsAsyncFunction: AwsAsyncFunction[Req, Res])(implicit ec: ExecutionContext): Future[List[Res]] = {
def impl(nextToken: Option[String] = Some(null), acc: List[Res] = Nil): Future[List[Res]] = nextToken match {
case None ? Future.successful(acc.reverse)
case Some(token) ?
val req = requestFactory()
req.setNextToken(token)
req.via(awsAsyncFunction)
.flatMap(res ? impl(Option(res.getNextToken()), res :: acc))
}
impl()
}
}
def fetchAll[Req <: PaginatedRequest, Res <: PaginatedResult](requestFactory: () ? Req,
awsAsyncFunction: AwsAsyncFunction[Req, Res])
(implicit ec: ExecutionContext): Future[List[Res]] = fetchAllWithRequestsLike(requestFactory).via(awsAsyncFunction)
def fetchAllWithRequestsLike[Req <: PaginatedRequest, Res <: PaginatedResult](requestFactory: () ? Req): PaginatedResponseRetriever[Req, Res] =
new PaginatedResponseRetriever(requestFactory)
def fetchAllWithDefaultRequestsVia[Req <: PaginatedRequest : ClassTag, Res <: PaginatedResult](awsAsyncFunction: AwsAsyncFunction[Req, Res])
(implicit ec: ExecutionContext): Future[List[Res]] =
fetchAllWithRequestsLike(() ? implicitly[ClassTag[Req]].runtimeClass.newInstance().asInstanceOf[Req]).via(awsAsyncFunction)
}
开发者ID:Dwolla,项目名称:scala-aws-utils,代码行数:38,代码来源:PaginatedResponseRetriever.scala
示例10: MessageEventProcessor
//设置package包名称以及导入依赖的类
package sample.helloworldconsumer.impl
import akka.Done
import com.datastax.driver.core.{BoundStatement, PreparedStatement}
import com.lightbend.lagom.scaladsl.persistence.ReadSideProcessor.ReadSideHandler
import com.lightbend.lagom.scaladsl.persistence.cassandra.{CassandraReadSide, CassandraSession}
import com.lightbend.lagom.scaladsl.persistence.{AggregateEventTag, EventStreamElement, ReadSideProcessor}
import scala.concurrent.{ExecutionContext, Future}
class MessageEventProcessor(cassandraReadSide: CassandraReadSide, cassandraSession: CassandraSession)
(implicit ec: ExecutionContext) extends ReadSideProcessor[MessageEvent] {
private var insertWordStmt: PreparedStatement = _
override def buildHandler(): ReadSideHandler[MessageEvent] = {
cassandraReadSide.builder[MessageEvent]("message_offset")
.setGlobalPrepare(createTable)
.setPrepare { tags =>
prepareStatements
}
.setEventHandler[MessageSaved](insertWord)
.build()
}
override def aggregateTags: Set[AggregateEventTag[MessageEvent]] = Set(MessageEventTag.INSTANCE)
private def createTable(): Future[Done] = {
for {
_ <- cassandraSession.executeCreateTable(
""" CREATE TABLE IF NOT EXISTS wordcounttest (
words text,
insertion_time timestamp,
PRIMARY KEY (words,insertion_time)
)WITH CLUSTERING ORDER BY (insertion_time DESC)
""")
} yield Done
}
private def prepareStatements(): Future[Done] = {
for {
insert <- cassandraSession.prepare(
"""insert into wordcounttest(words ,insertion_time) values(? ,toTimestamp(now())) """)
} yield {
insertWordStmt = insert
Done
}
}
private def insertWord(started: EventStreamElement[MessageSaved]): Future[List[BoundStatement]] = {
Future.successful {
val words = started.event.msg.replaceAll("[^\\p{L}\\p{Nd}]+", " ").split(" ").toList
words.map{ word=> insertWordStmt.bind(word) }
}
}
}
开发者ID:knoldus,项目名称:lagom-scala-wordcount.g8,代码行数:59,代码来源:MessageEventProcessor.scala
示例11: ExecutionContextBackboneCoordinator
//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent
import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try
import scala.util.control.NonFatal
import org.slf4j.LoggerFactory
import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }
class ExecutionContextBackboneCoordinator[DA](backbone: Backbone[DA], executionContext: ExecutionContext) {
import ExecutionContextBackboneCoordinator._
val localInitPhases = backbone.initializeTopLevelContexts
def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
Future {
val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
try {
backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
} finally {
releasePhases.foreach((phase: LocalReleasePhase) => {
Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
})
}
}(executionContext)
}
}
object ExecutionContextBackboneCoordinator {
val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
}
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:37,代码来源:ExecutionContextBackboneCoordinator.scala
示例12: QQAsyncTestSuite
//设置package包名称以及导入依赖的类
package qq
import java.util.concurrent.TimeUnit
import monix.execution.schedulers.ExecutionModel
import monix.execution.{Cancelable, Scheduler}
import org.scalatest.AsyncFreeSpec
import scala.concurrent.ExecutionContext
abstract class QQAsyncTestSuite extends AsyncFreeSpec with QQTestSuite with AsyncTestUtil {
implicit val schedulerVal: Scheduler = scheduler(super.executionContext)
def scheduler(implicit executionContext: ExecutionContext): Scheduler =
new Scheduler {
override def execute(runnable: Runnable): Unit = executionContext.execute(runnable)
override def reportFailure(t: Throwable): Unit = executionContext.reportFailure(t)
override def scheduleOnce(initialDelay: Long, unit: TimeUnit, r: Runnable): Cancelable = {
executionContext.execute(r)
Cancelable.empty
}
override def scheduleWithFixedDelay(initialDelay: Long, delay: Long, unit: TimeUnit, r: Runnable): Cancelable = {
???
}
override def scheduleAtFixedRate(initialDelay: Long, period: Long, unit: TimeUnit, r: Runnable): Cancelable = {
???
}
override def currentTimeMillis(): Long = System.currentTimeMillis()
override def executionModel: ExecutionModel = ExecutionModel.SynchronousExecution
override def withExecutionModel(em: ExecutionModel): Scheduler = ???
}
}
开发者ID:edmundnoble,项目名称:slate,代码行数:35,代码来源:QQAsyncTestSuite.scala
示例13: Hello
//设置package包名称以及导入依赖的类
package com.github.cupenya.hello
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.{ AuthorizationFailedRejection, Directives, RejectionHandler }
import akka.http.scaladsl.model.StatusCodes._
import com.github.cupenya.hello.authentication.AuthorizationDirectives
import spray.json._
import scala.concurrent.ExecutionContext
case class Hello(message: String)
case class AuthError(error: String)
trait Protocols extends DefaultJsonProtocol {
implicit val helloFormat = jsonFormat1(Hello)
}
trait HelloHttpService extends Directives with AuthorizationDirectives with SprayJsonSupport with Protocols with Logging {
implicit val ec: ExecutionContext
implicit val authErrorFormat = jsonFormat1(AuthError)
private val rh = RejectionHandler.newBuilder().handle {
case AuthorizationFailedRejection =>
complete(Forbidden -> AuthError("The supplied authentication is not authorized to access this resource"))
}.result()
val helloRoute = handleRejections(rh) {
authorized { authInfo =>
pathPrefix("hello") {
get {
complete(Hello(s"hello ${authInfo.userId}"))
}
}
}
}
}
开发者ID:cupenya,项目名称:hello-world-microservice,代码行数:39,代码来源:HelloHttpService.scala
示例14: LocationController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
//import models.City
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import play.modules.reactivemongo._
import reactivemongo.play.json.collection._
import utils.Errors
import models._
import scala.concurrent.{ExecutionContext, Future}
import play.modules.reactivemongo.json._
@Singleton
class LocationController @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) extends Controller with MongoController with ReactiveMongoComponents {
def locationFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("location"))
def create(lat: Double, long: Double) = Action.async {
for {
locations <- locationFuture
lastError <- locations.insert(Location(lat, long))
} yield
Ok("Mongo LastError: %s".format(lastError))
}
def createFromJson = Action.async(parse.json) { request =>
Json.fromJson[Location](request.body) match {
case JsSuccess(location, _) =>
for {
locations <- locationFuture
lastError <- locations.insert(location)
} yield {
Logger.debug(s"Successfully inserted with LastError: $lastError")
Created("Created 1 location")
}
case JsError(errors) =>
Future.successful(BadRequest("Could not build a location from the json provided. " + Errors.show(errors)))
}
}
}
开发者ID:Yashar78,项目名称:play,代码行数:47,代码来源:LocationController.scala
示例15: RegistryClient
//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.protocol.registry
import scala.concurrent.{ ExecutionContext, Future }
import akka.actor.ActorSystem
import akka.event.slf4j.SLF4JLogging
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.headers.{ Authorization, OAuth2BearerToken }
import akka.http.scaladsl.model.{ HttpRequest, HttpResponse, RequestEntity }
import akka.stream.Materializer
import fommil.sjs.FamilyFormats._
class RegistryClient(baseUrl: String = "http://api.flowhub.io") extends SLF4JLogging {
def register(runtime: Runtime, token: String)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext): Future[HttpResponse] = {
log.debug(s"PUT $baseUrl/runtimes/${runtime.id}")
Marshal(runtime).to[RequestEntity].flatMap { entity =>
Http().singleRequest(HttpRequest(
PUT,
s"$baseUrl/runtimes/${runtime.id}",
List(Authorization(OAuth2BearerToken(token))),
entity))
}
}
def unregister(runtimeId: String, token: String)(implicit system: ActorSystem, mat: Materializer): Future[HttpResponse] = {
log.debug(s"DELETE $baseUrl/runtimes/$runtimeId")
Http().singleRequest(HttpRequest(
DELETE,
s"$baseUrl/runtimes/$runtimeId",
List(Authorization(OAuth2BearerToken(token)))))
}
}
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:37,代码来源:RegistryClient.scala
示例16: EventClientActor
//设置package包名称以及导入依赖的类
package com.bob.scalatour.akka.cluster
import akka.actor.{Props, ActorSystem, ActorRef, Actor}
import com.typesafe.config.ConfigFactory
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext
import scala.concurrent.forkjoin.ForkJoinPool
class EventClientActor extends Actor {
implicit val ec: ExecutionContext = ExecutionContext.fromExecutor(new ForkJoinPool())
val events = Map(
"2751" -> List(
"""10.10.2.72 [21/Aug/2015:18:29:19 +0800] "GET /t.gif?installid=0000lAOX&udid=25371384b2eb1a5dc5643e14626ecbd4&sessionid=25371384b2eb1a5dc5643e14626ecbd41440152875362&imsi=460002830862833&operator=1&network=1×tamp=1440152954&action=14&eventcode=300039&page=200002& HTTP/1.0" "-" 204 0 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.4; R8207 Build/KTU84P)" "121.25.190.146"""",
"""10.10.2.8 [21/Aug/2015:18:29:19 +0800] "GET /t.gif?installid=0000VACO&udid=f6b0520cbc36fda6f63a72d91bf305c0&imsi=460012927613645&operator=2&network=1×tamp=1440152956&action=1840&eventcode=100003&type=1&result=0& HTTP/1.0" "-" 204 0 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.2; GT-I9500 Build/KOT49H)" "61.175.219.69""""
),
"2752" -> List(
"""10.10.2.72 [21/Aug/2015:18:29:19 +0800] "GET /t.gif?installid=0000gCo4&udid=636d127f4936109a22347b239a0ce73f&sessionid=636d127f4936109a22347b239a0ce73f1440150695096&imsi=460036010038180&operator=3&network=4×tamp=1440152902&action=1566&eventcode=101010&playid=99d5a59f100cb778b64b5234a189e1f4&radioid=1100000048450&audioid=1000001535718&playtime=3& HTTP/1.0" "-" 204 0 "-" "Dalvik/1.6.0 (Linux; U; Android 4.4.4; R8205 Build/KTU84P)" "106.38.128.67"""",
"""10.10.2.72 [21/Aug/2015:18:29:19 +0800] "GET /t.gif?installid=0000kPSC&udid=2ee585cde388ac57c0e81f9a76f5b797&operator=0&network=1×tamp=1440152968&action=6423&eventcode=100003&type=1&result=0& HTTP/1.0" "-" 204 0 "-" "Dalvik/v3.3.85 (Linux; U; Android L; P8 Build/KOT49H)" "202.103.133.112"""",
"""10.10.2.72 [21/Aug/2015:18:29:19 +0800] "GET /t.gif?installid=0000lABW&udid=face1161d739abacca913dcb82576e9d&sessionid=face1161d739abacca913dcb82576e9d1440151582673&operator=0&network=1×tamp=1440152520&action=1911&eventcode=101010&playid=b07c241010f8691284c68186c42ab006&radioid=1100000000762&audioid=1000001751983&playtime=158& HTTP/1.0" "-" 204 0 "-" "Dalvik/1.6.0 (Linux; U; Android 4.1; H5 Build/JZO54K)" "221.232.36.250""""
),
"2753" -> List(
"""10.10.2.8 [21/Aug/2015:18:29:19 +0800] "GET /t.gif?installid=0000krJw&udid=939488333889f18e2b406d2ece8f938a&sessionid=939488333889f18e2b406d2ece8f938a1440137301421&imsi=460028180045362&operator=1&network=1×tamp=1440152947&action=1431&eventcode=300030&playid=e1fd5467085475dc4483d2795f112717&radioid=1100000001123&audioid=1000000094911&playtime=951992& HTTP/1.0" "-" 204 0 "-" "Dalvik/1.6.0 (Linux; U; Android 4.0.4; R813T Build/IMM76D)" "5.45.64.205"""",
"""10.10.2.72 [21/Aug/2015:18:29:19 +0800] "GET /t.gif?installid=0000kcpz&udid=cbc7bbb560914c374cb7a29eef8c2144&sessionid=cbc7bbb560914c374cb7a29eef8c21441440152816008&imsi=460008782944219&operator=1&network=1×tamp=1440152873&action=360&eventcode=200003&page=200003&radioid=1100000046018& HTTP/1.0" "-" 204 0 "-" "Dalvik/v3.3.85 (Linux; U; Android 4.4.2; MX4S Build/KOT49H)" "119.128.106.232"""",
"""10.10.2.8 [21/Aug/2015:18:29:19 +0800] "GET /t.gif?installid=0000juRL&udid=3f9a5ffa69a5cd5f0754d2ba98c0aeb2&imsi=460023744091238&operator=1&network=1×tamp=1440152957&action=78&eventcode=100003&type=1&result=0& HTTP/1.0" "-" 204 0 "-" "Dalvik/v3.3.85 (Linux; U; Android 4.4.3; S?MSUNG. Build/KOT49H)" "223.153.72.78""""
)
)
val ports = Seq("2751", "2752", "2753")
val actors = scala.collection.mutable.HashMap[String, ActorRef]()
ports.foreach(port => {
val config = ConfigFactory.parseString(s"akka.remote.netty.tcp.port=${port}")
.withFallback(ConfigFactory.parseString("akka.cluster.roles = [collector]"))
.withFallback(ConfigFactory.load())
val system = ActorSystem("event-cluster-system", config)
actors(port) = system.actorOf(Props[EventCollector], name = "collectingActor")
})
Thread.sleep(30000)
context.system.scheduler.schedule(0 millis, 5000 millis) {
ports.foreach(port => {
events(port).foreach(line => {
println("RAW: port=" + port + ", line=" + line)
actors(port) ! RawNginxRecord("host.me:" + port, line)
})
})
}
override def receive: Receive = {
case _ =>
}
}
开发者ID:bobxwang,项目名称:scalatour,代码行数:59,代码来源:EventClientActor.scala
示例17: AsyncTest
//设置package包名称以及导入依赖的类
package com.bob.scalatour.futures
import org.scalatest.FunSuite
import scala.async.Async._
import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success}
class AsyncTest extends FunSuite {
implicit val ec = ExecutionContext.global
test("sequential") {
val future = async {
val futureOne = async {
1
}
val futureTwo = async {
2
}
await(futureOne) + await(futureTwo)
}
future onComplete {
case Success(result) => assert(result == 3)
case Failure(failure) => throw failure
}
}
test("parallel") {
val futureOne = async {
1
}
val futureTwo = async {
2
}
val futureThree = async {
await(futureOne) + await(futureTwo)
}
futureThree onComplete {
case Success(result) => assert(result == 3)
case Failure(failure) => throw failure
}
}
}
开发者ID:bobxwang,项目名称:scalatour,代码行数:46,代码来源:AsyncTest.scala
示例18: UserService
//设置package包名称以及导入依赖的类
package dbspike
import scala.concurrent.Future
import scala.concurrent.ExecutionContext
import concurrent.ExecutionContext.Implicits.global
object UserService {
def addUser(user: User): String = {
Users.add(user)
}
def deleteUser(id: Long): Option[Int] = {
Users.delete(id)
}
def getUser(id: Long): Option[User] = {
Users.get(id)
}
def listAllUsers: Seq[User] = {
Users.listAll
}
}
开发者ID:tflander,项目名称:cmibookkeeping,代码行数:26,代码来源:UserService.scala
示例19: 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:Starofall,项目名称:Chakka,代码行数:41,代码来源:PipeToSupport.scala
示例20: ExampleFilter
//设置package包名称以及导入依赖的类
package filters
import akka.stream.Materializer
import javax.inject._
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class ExampleFilter @Inject()(
implicit override val mat: Materializer,
exec: ExecutionContext) extends Filter {
override def apply(nextFilter: RequestHeader => Future[Result])
(requestHeader: RequestHeader): Future[Result] = {
// Run the next filter in the chain. This will call other filters
// and eventually call the action. Take the result and modify it
// by adding a new header.
nextFilter(requestHeader).map { result =>
// result.withHeaders("X-ExampleFilter" -> "foo")
result
}
}
}
开发者ID:morpheby,项目名称:ntcu-control-server,代码行数:26,代码来源:ExampleFilter.scala
注:本文中的scala.concurrent.ExecutionContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论