本文整理汇总了Scala中akka.util.Timeout类的典型用法代码示例。如果您正苦于以下问题:Scala Timeout类的具体用法?Scala Timeout怎么用?Scala Timeout使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Timeout类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Main
//设置package包名称以及导入依赖的类
package onextent.oemap.server
import com.typesafe.scalalogging.LazyLogging
import scala.concurrent.duration._
import akka.actor._
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.{Config, ConfigFactory}
object Main extends LazyLogging with App with RestInterface {
val config: Config = ConfigFactory.load().getConfig("main")
val logLevel: String = config.getString("logLevel")
val appName: String = config.getString("appName")
val host: String = config.getString("host")
val port: Int = config.getInt("port")
implicit val system = ActorSystem("map-management-service")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
implicit val timeout = Timeout(10 seconds)
val api = routes
Http().bindAndHandle(handler = api, interface = host, port = port) map {
binding =>
logger.info(s"REST interface bound to ${binding.localAddress}")
} recover {
case ex =>
logger.error(s"REST interface could not bind to $host:$port",
ex.getMessage)
}
}
示例2: 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
}
}
示例3: Request
//设置package包名称以及导入依赖的类
package org.freetrm.eventstore.http
import akka.actor.{ActorRef, ActorSystem}
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.Config
import org.freetrm.eventstore.utils.Log
import org.freetrm.eventstore.{EventSourceReader, EventSourceWriter}
import scaldi.Module
import scala.concurrent.Future
import scala.concurrent.duration._
case class Request(client: ActorRef, req: HttpRequest)
class WebService extends Module with Log {
implicit lazy val system = inject[ActorSystem]
implicit lazy val mat = ActorMaterializer()
def start(): Future[ServerBinding] = {
val conf = inject[Config]
implicit val timeout = Timeout(5.seconds)
val interface = conf.getString("www-service.interface")
val port = conf.getInt("www-service.port")
log.info(s"Starting http server on $interface:$port")
Http().bindAndHandle(service.flow, interface, port)
}
def stop() {}
def service: EventStoreHttpServer = {
implicit val system = inject[ActorSystem]
val conf = inject[Config]
val cookie = conf.getString("www-service.cookie")
new EventStoreHttpServer(
inject[EventSourceWriter],
inject[EventSourceReader],
cookie)
}
}
示例4: User
//设置package包名称以及导入依赖的类
package com.sunway.model
import akka.util.Timeout
import com.github.dunnololda.scage.support.Vec
import com.sunway.screen.gamescreen.Character
import com.sunway.util.MutableString
import scala.collection.mutable.ArrayBuffer
import scala.concurrent.duration._
object User {
val WAITING_STATE = 0
val READY_STATE = 1
val maxPlayerInRoom = 2
val HOST_ROOM_ID = 0
implicit val timeout = Timeout(5.seconds)
val targetRoomNum: MutableString = new MutableString("0")
var myName: MutableString = new MutableString(System.getProperty("user.name"))
var myRoomPos: MutableString = new MutableString("")
var myPassword: MutableString = new MutableString("")
var playerNames = Array.fill[MutableString](maxPlayerInRoom)(new MutableString(""))
var playerRoomStats = Array.fill[MutableString](maxPlayerInRoom)(new MutableString(""))
var gameState = WAITING_STATE
var mapState = WAITING_STATE
var readyPlay = false
var roomStateSeenUser = new MutableString("WAITING STATE")
var newPlayerJoining = false
var newPlayerPos: Option[Int] = None
var newPlayerVec = Vec()
var oldPlayerLeave = false
var oldPlayerPos: Option[Int] = None
//GAMEPLAY
var charactersPos: Array[Vec] = Array(Vec(20, ConfigurationObject.windowHeight / 2 - 70), (Vec(150, ConfigurationObject.windowHeight / 2 - 70)))
var charactersObj = Array.fill[Character](maxPlayerInRoom)(null)
var mapInformation = List[ArrayBuffer[Tuple2[Float, Float]]]()
}
示例5: TestKitExtension
//设置package包名称以及导入依赖的类
package akka.testkit
import com.typesafe.config.Config
import akka.util.Timeout
import akka.actor.{ ExtensionId, ActorSystem, Extension, ExtendedActorSystem }
import scala.concurrent.duration.FiniteDuration
object TestKitExtension extends ExtensionId[TestKitSettings] {
override def get(system: ActorSystem): TestKitSettings = super.get(system)
def createExtension(system: ExtendedActorSystem): TestKitSettings = new TestKitSettings(system.settings.config)
}
class TestKitSettings(val config: Config) extends Extension {
import akka.util.Helpers._
val TestTimeFactor = config.getDouble("akka.test.timefactor").
requiring(tf ? !tf.isInfinite && tf > 0, "akka.test.timefactor must be positive finite double")
val SingleExpectDefaultTimeout: FiniteDuration = config.getMillisDuration("akka.test.single-expect-default")
val TestEventFilterLeeway: FiniteDuration = config.getMillisDuration("akka.test.filter-leeway")
val DefaultTimeout: Timeout = Timeout(config.getMillisDuration("akka.test.default-timeout"))
}
示例6: TransactorExtension
//设置package包名称以及导入依赖的类
package akka.transactor
import akka.actor.{ ActorSystem, ExtensionId, ExtensionIdProvider, ExtendedActorSystem }
import akka.actor.Extension
import com.typesafe.config.Config
import akka.util.Timeout
import scala.concurrent.duration.Duration
import java.util.concurrent.TimeUnit.MILLISECONDS
@deprecated("akka.transactor will be removed", "2.3")
object TransactorExtension extends ExtensionId[TransactorSettings] with ExtensionIdProvider {
override def get(system: ActorSystem): TransactorSettings = super.get(system)
override def lookup: TransactorExtension.type = TransactorExtension
override def createExtension(system: ExtendedActorSystem): TransactorSettings = new TransactorSettings(system.settings.config)
}
@deprecated("akka.transactor will be removed", "2.3")
class TransactorSettings(val config: Config) extends Extension {
import config._
val CoordinatedTimeout: Timeout = Timeout(Duration(getMilliseconds("akka.transactor.coordinated-timeout"), MILLISECONDS))
}
示例7: ActorSpec
//设置package包名称以及导入依赖的类
package com.github.j5ik2o.reactive.redis
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.testkit.{ ImplicitSender, TestKit }
import akka.util.Timeout
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{ BeforeAndAfterAll, DiagrammedAssertions, FunSpecLike }
import scala.concurrent.duration._
abstract class ActorSpec(_system: ActorSystem)
extends TestKit(_system)
with ImplicitSender
with FunSpecLike
with DiagrammedAssertions
with BeforeAndAfterAll
with TimeFactorSupport
with ScalaFutures {
implicit override val patienceConfig: PatienceConfig = PatienceConfig(15 * timeFactor seconds)
implicit val materializer = ActorMaterializer()
implicit val timeout = Timeout(15 seconds)
override protected def afterAll(): Unit = {
shutdown()
super.beforeAll()
}
}
示例8: GoogleBooksApiStub
//设置package包名称以及导入依赖的类
package org.packtpublishing.stub
import akka.actor.{ActorSystem, Props}
import akka.io.IO
import akka.pattern._
import akka.util.Timeout
import scala.concurrent.Await
import scala.concurrent.duration._
import spray.can.Http
import spray.can.server.ServerSettings
import spray.routing._
import Directives._
class GoogleBooksApiStub(val route: Route) {
implicit val system = ActorSystem("google-books-api")
implicit val timeout: Timeout = 3 seconds
val settings = ServerSettings(system).copy(sslEncryption = false)
val handler = system.actorOf(Props(new GoogleBooksRestService(route)), name = "handler")
def start(port: Int) =
Await.ready(IO(Http) ? Http.Bind(handler,
interface = "localhost", port = port, settings = Some(settings)), timeout.duration)
def stop() = {
IO(Http) ? Http.CloseAll
system.stop(handler)
}
}
sealed class GoogleBooksRestService(val route: Route) extends HttpServiceActor {
def receive = runRoute {
route
}
}
示例9: HttpClientAsActor
//设置package包名称以及导入依赖的类
package com.scalaio.http.client.actor
import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model._
import akka.stream.{ActorMaterializer, ActorMaterializerSettings}
import akka.util.{ByteString, Timeout}
import play.api.libs.json.Json
import scala.concurrent.Future
import scala.concurrent.duration._
class HttpClientAsActor(notifier: ActorRef) extends Actor with ActorLogging {
import akka.pattern.pipe
import context.dispatcher
implicit val timeout = Timeout(5 seconds)
implicit val materializer = ActorMaterializer(ActorMaterializerSettings(context.system))
val http = Http(context.system)
override def preStart() = {
http
.singleRequest(HttpRequest(method = GET, uri = "https://jsonplaceholder.typicode.com/posts/1"))
.pipeTo(self)
}
def receive = {
case HttpResponse(StatusCodes.OK, headers, entity, _) =>
val response: Future[ByteString] = entity.dataBytes.runFold(ByteString(""))(_ ++ _)
log.info(s"got response $headers $entity")
response pipeTo self
context become handlingMessage
case [email protected](code, _, _, _) =>
log.warning("Request failed, response code: " + code)
resp.discardEntityBytes()
}
def handlingMessage: Receive = {
case content: ByteString =>
log.info("Success was OK: " + content)
val contentAsString = (Json.parse(content.utf8String) \ "title").as[String]
notifier ! contentAsString
context become receive
}
}
object HttpClientAsActor {
def props(notifier: ActorRef) = Props(classOf[HttpClientAsActor], notifier)
}
示例10: SampleRoutes
//设置package包名称以及导入依赖的类
package com.queirozf.routes
import java.util.concurrent.TimeUnit
import akka.actor.ActorSystem
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.util.Timeout
import com.queirozf.utils.ResponseUtils._
class SampleRoutes(implicit val system: ActorSystem) {
import system.dispatcher
implicit val timeout = Timeout(32, TimeUnit.MILLISECONDS)
// sample route: localhost:5000/v1/999/test
def routes = {
pathPrefix(LongNumber) { param =>
path("test") {
get {
getTest(param)
}
}
}
}
private def getTest(param: Long): Route = {
complete {
JsonOk(param.toString)
}
}
}
示例11: Main
//设置package包名称以及导入依赖的类
package com.bau5.sitetracker.server
import akka.actor.PoisonPill
import akka.util.Timeout
import com.bau5.sitetracker.common.BaseProvider
import com.bau5.sitetracker.common.Events.{Message, MessageAll, SaveRequest}
import scala.concurrent.duration._
import scala.io.StdIn
object Main extends BaseProvider("ServerSystem", "") {
override implicit val timeout: Timeout = Timeout(5 seconds)
val messageAll = "message-all (.+)".r
def main(args: Array[String]) {
val serverActor = newActor[ServerActor]("server")
serverActor ! LoadSavedData
while (true) StdIn.readLine("> ") match {
case "save" =>
serverActor ! SaveRequest
case "quit" =>
serverActor ! SaveRequest
serverActor ! PoisonPill
sys.exit(0)
case messageAll(msg) =>
serverActor ! MessageAll(Message(msg))
case _ =>
println("Unrecognized input.")
}
}
}
示例12: handleProof
//设置package包名称以及导入依赖的类
package wow.auth.handlers
import akka.pattern.ask
import akka.util.Timeout
import wow.auth.AccountsState
import wow.auth.AccountsState.IsOnline
import wow.auth.data.Account
import wow.auth.protocol.AuthResults
import wow.auth.protocol.packets.{ClientLogonProof, ServerLogonProof, ServerLogonProofFailure, ServerLogonProofSuccess}
import wow.auth.session.AuthSession.EventIncoming
import wow.auth.session._
import wow.auth.utils.PacketSerializer
import scala.concurrent.Await
import scala.concurrent.duration._
trait LogonProofHandler {
this: AuthSession =>
def handleProof: StateFunction = {
case Event(EventIncoming(bits), ChallengeData(login, srp6Identity, srp6Challenge)) =>
log.debug("Received proof")
val packet = PacketSerializer.deserialize[ClientLogonProof](bits)
log.debug(packet.toString)
srp6.verify(login, packet.clientKey, packet.clientProof, srp6Identity, srp6Challenge) match {
case Some(srp6Validation) =>
val accountState = context.actorSelection(AccountsState.ActorPath)
implicit val timeout = Timeout(5 seconds)
val askIsOnline = (accountState ? IsOnline(login)).mapTo[Boolean]
val isOnline = Await.result(askIsOnline, timeout.duration)
if (isOnline) {
sendPacket(ServerLogonProof(AuthResults.FailAlreadyOnline, None, Some(ServerLogonProofFailure())))
goto(StateFailed) using NoData
} else {
Account.saveSessionKey(login, srp6Validation.sharedKey)
sendPacket(ServerLogonProof(AuthResults.Success,
Some(ServerLogonProofSuccess(srp6Validation.serverProof)),
None))
goto(StateRealmlist) using NoData
}
case None =>
sendPacket(ServerLogonProof(AuthResults.FailUnknownAccount, None, Some(ServerLogonProofFailure())))
goto(StateFailed) using NoData
}
}
}
示例13: Withdraw
//设置package包名称以及导入依赖的类
package akka_in_action.STM
import scala.concurrent.stm.atomic
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.util.Timeout
import scala.concurrent.duration._
case class Withdraw(amount:Int)
case class Deposit(amount:Int)
case class TransferMessage(amount: Int,
from: ActorRef,
to: ActorRef)
class Account(name: String, var balance: Int) extends Actor {
override def receive: Receive = {
case Withdraw(amount) => {
if(this.balance > amount) {
this.balance -= this.balance
println(s"${name} withdraw: ${amount}, balance: ${balance}")
} else throw new Exception("insufficient balance")
}
case Deposit(amount) => {
this.balance += amount
println(s"${name} deposit: ${amount}, balance: ${balance}")
}
}
}
class Transfer extends Actor {
implicit val timeout = new Timeout(1 seconds)
override def preRestart(reason: Throwable, message: Option[Any]): Unit = {
message.foreach(_ => sender ! "Failed")
super.preRestart(reason, message)
}
override def receive: Receive = {
case TransferMessage(amount, from, to) => {
atomic { implicit tnx => {
from ! Withdraw(amount)
to ! Deposit(amount)
}}
}
}
}
object TransferTransaction extends App {
implicit val system = ActorSystem("actor-system")
import system.dispatcher
val transfer = system.actorOf(Props(new Transfer), "transfer")
val from = system.actorOf(Props(new Account("from", 60)))
val to = system.actorOf(Props(new Account("to", 20)))
transfer ! TransferMessage(70, from, to)
}
示例14: Boot
//设置package包名称以及导入依赖的类
package com.zhranklin.homepage
import java.io.InputStream
import java.security.{KeyStore, SecureRandom}
import javax.net.ssl._
import akka.http.scaladsl._
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import scala.concurrent.duration._
import scala.io.{Source, StdIn}
object Boot extends App with MyRouteService {
import ActorImplicits._
implicit val timeout = Timeout(5.seconds)
val conf = ConfigFactory.load().getConfig("settings.server")
val host = conf.getString("host")
val httpBindingFuture = Http().bindAndHandle(myRoute, host, conf.getInt("http_port"))
val httpsBindingFuture =
Http().bindAndHandle(myRoute, host, conf.getInt("https_port"), SSLConfig.https)
println(s"Server online at http://$host:8080/\nPress RETURN to stop...")
if (System.getProperty("dev") != null) {
StdIn.readLine() // let it run until user presses return
Seq(httpBindingFuture, httpsBindingFuture).foreach { _
.flatMap(_.unbind())
.onComplete(_ ? system.terminate())
}
}
}
object SSLConfig {
val https: HttpsConnectionContext = {
val password: Array[Char] = Source.fromInputStream(getClass.getClassLoader.getResourceAsStream("password")).toArray.filter(_ != '\n')
val ks: KeyStore = KeyStore.getInstance("jks")
val keystore: InputStream = getClass.getClassLoader.getResourceAsStream("zhranklin.com.jks")
require(keystore != null, "Keystore required!")
ks.load(keystore, password)
val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance("SunX509")
keyManagerFactory.init(ks, password)
val tmf: TrustManagerFactory = TrustManagerFactory.getInstance("SunX509")
tmf.init(ks)
val sslContext: SSLContext = SSLContext.getInstance("TLS")
sslContext.init(keyManagerFactory.getKeyManagers, tmf.getTrustManagers, new SecureRandom)
ConnectionContext.https(sslContext)
}
}
示例15: AkkademyDbSpec
//设置package包名称以及导入依赖的类
import akka.actor.{ActorSystem, Props}
import akka.testkit.TestActorRef
import akka.util.Timeout
import com.example.{AkkademyDb, ScalaPongActor, SetRequest}
import org.scalatest.{FunSpecLike, _}
import scala.concurrent.duration._
class AkkademyDbSpec extends FunSpecLike with Matchers {
implicit val system = ActorSystem()
implicit val timeout = Timeout(5 seconds)
describe("akkademyDb") {
describe("given SetRequest") {
it("should place key/value into your map") {
val actorRef = TestActorRef(new AkkademyDb)
actorRef ! SetRequest("key", "value")
val akkademyDb = actorRef.underlyingActor
akkademyDb.map.get("key") should equal(Some("value"))
}
}
}
}
class ScalaPongActorSpec extends FunSpecLike with Matchers {
implicit val system = ActorSystem()
implicit val timeout = Timeout(5 seconds)
describe("scalaPongActor") {
describe("given Ping") {
it("should return message Pong") {
val actorRef = system.actorOf(Props[ScalaPongActor], "PongFoo")
actorRef ! "ping"
true
}
}
}
}