本文整理汇总了Scala中com.twitter.util.Await类的典型用法代码示例。如果您正苦于以下问题:Scala Await类的具体用法?Scala Await怎么用?Scala Await使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Await类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Foo2
//设置package包名称以及导入依赖的类
package com.bluedit
import com.twitter.finagle.http.{Response, Request}
import com.twitter.finagle.{Service, Http}
import com.twitter.util.Await
import io.finch._
import io.finch.circe._
import io.circe.generic.auto._
import shapeless.{CNil, :+:}
import io.circe._, io.circe.generic.auto._, io.circe.syntax._
case class Foo2( f: String )
case class Bar2( b: String )
case class Person2( firstname: String, lastname: String )
object HelloService4 extends App {
val foo2: Endpoint[Foo2] = get("foo" / string ) {
name: String => Ok( Foo2(name))
}
val bar2: Endpoint[Bar2] = get("bar" / string ) {
name: String => Ok( Bar2(name))
}
val person2: Endpoint[Person2] = get("person" / string ) {
name: String => Ok( Person2( name, "Welkenbach"))
}
val api: Service[Request, Response] = (foo2 :+: bar2 :+: person2).toService
Await.ready(Http.server.serve(":9001", api ))
}
示例2: WebserverApp
//设置package包名称以及导入依赖的类
import java.security.KeyStore
import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory}
import com.twitter.finagle.Http
import com.twitter.util.Await
import io.circe.generic.auto._
import io.finch._
import io.finch.circe._
object WebserverApp extends App {
def getSSLContext: SSLContext = {
// Create and initialize the SSLContext with key material
val passphrase = "sample".toCharArray()
val trustPassphrase = "sample".toCharArray()
// First initialize the key and trust material
val ksKeys = KeyStore.getInstance("JKS")
val keystoreResource = this.getClass.getClassLoader.getResourceAsStream("sample-keystore.jks")
ksKeys.load(keystoreResource, passphrase)
val ksTrust = KeyStore.getInstance("JKS")
val trustStoreResource = this.getClass.getClassLoader.getResourceAsStream("sample-keystore.jks")
ksTrust.load(trustStoreResource, trustPassphrase)
// KeyManagers decide which key material to us
val kmf = KeyManagerFactory.getInstance("SunX509")
kmf.init(ksKeys, passphrase)
// TrustManagers decide whether to allow connections
val tmf = TrustManagerFactory.getInstance("SunX509")
tmf.init(ksTrust)
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(kmf.getKeyManagers, tmf.getTrustManagers, null)
sslContext
}
def sample: Endpoint[String] =
get("sample") {
Ok("Was it a TLS connection?... probably not")
}
val routes = sample
val server = Http.server
.withTransport.tls(getSSLContext)
.serve(s":38082", routes.handle {
case e: Exception =>
InternalServerError(e)
}.toService)
println("Server running on :38082")
Await.result(server)
}
示例3:
//设置package包名称以及导入依赖的类
package app.module
import app.config.application.ApplicationProperty
import app.v1.Api
import com.twitter.finagle.Http
import com.twitter.logging.Logger
import com.twitter.util.{ Await, Duration, StorageUnit }
trait ServerModule {
self: com.twitter.app.App with Api with ApplicationProperty =>
private val log = Logger.get(getClass)
premain {
log.info("[Finch] server is starting ...")
val server = Http.server
.withLabel(applicationProperty.systemId)
.withRequestTimeout(Duration.fromSeconds(applicationProperty.requestTimeoutInSeconds))
.withMaxRequestSize(StorageUnit.fromMegabytes(applicationProperty.maxRequestSizeInMB))
.configured(Http.Netty4Impl)
.serve(s":${applicationProperty.applicationPort}", apiService)
onExit {
server.close()
}
Await.result(server)
}
}
示例4: TemperatureSensorStatic
//设置package包名称以及导入依赖的类
package net.gutefrage.basic
import com.twitter.conversions.time._
import com.twitter.finagle.ThriftMux
import com.twitter.finagle.util.DefaultTimer
import com.twitter.server.TwitterServer
import com.twitter.util.{Await, Future}
import net.gutefrage.temperature.thrift._
import net.gutefrage.{Dtabs, Env}
import org.slf4j.bridge.SLF4JBridgeHandler
object TemperatureSensorStatic extends TwitterServer {
val env = flag[Env]("env", Env.Local, "environment this server runs")
premain {
SLF4JBridgeHandler.removeHandlersForRootLogger()
SLF4JBridgeHandler.install()
// initialise custom dtabs
Dtabs.init()
}
onExit {
log.info("Shutting down sensor")
}
def main(): Unit = {
// create a thrift client and resolve address via dtabs
val client = ThriftMux.client.newIface[TemperatureService.FutureIface](
// schema ! args
dest = s"zk2!127.0.0.1:2181!/service/${env().name}/temperature",
label = "temperature-sensor"
)
implicit val timer = DefaultTimer.twitter
val randomTemp = new java.util.Random()
def sendLoop: Future[Unit] = {
val datum = TemperatureDatum(randomTemp.nextInt(40) - 10,
System.currentTimeMillis / 1000)
log.info(s"Sending data: $datum")
for {
_ <- Future.sleep(1.second)
_ <- client.add(datum)
_ <- sendLoop
} yield ()
}
Await.ready(sendLoop)
}
}
示例5: failfastOnFlagsNotParsed
//设置package包名称以及导入依赖的类
package net.gutefrage.basic
import com.twitter.app.Flaggable
import com.twitter.conversions.time._
import com.twitter.finagle.{Dtab, ThriftMux}
import com.twitter.finagle.util.DefaultTimer
import com.twitter.server.TwitterServer
import com.twitter.util.{Await, Future}
import net.gutefrage.temperature.thrift._
import net.gutefrage.{Dtabs, Env}
import org.slf4j.bridge.SLF4JBridgeHandler
override def failfastOnFlagsNotParsed: Boolean = true
premain {
SLF4JBridgeHandler.removeHandlersForRootLogger()
SLF4JBridgeHandler.install()
// initialise custom dtabs
Dtabs.init(baseDtab())
log.info(
s"""|Use base dtab:
|${Dtab.base.show}
""".stripMargin)
}
onExit {
log.info("Shutting down sensor")
}
def main(): Unit = {
// create a thrift client and resolve address via dtabs
val client = ThriftMux.client.newIface[TemperatureService.FutureIface](
dest = "/s/temperature",
label = "temperature-sensor"
)
implicit val timer = DefaultTimer.twitter
val randomTemp = new java.util.Random()
def sendLoop: Future[Unit] = {
val datum = TemperatureDatum(randomTemp.nextInt(40) - 10,
System.currentTimeMillis / 1000)
log.info(s"Sending data: $datum")
for {
_ <- Future.sleep(1.second)
_ <- client.add(datum)
_ <- sendLoop
} yield ()
}
Await.ready(sendLoop)
}
}
示例6: WebServer
//设置package包名称以及导入依赖的类
package com.gilesc
package mynab
package finch
import com.gilesc.mynab.finch.endpoint.AccountEndpoints
import com.gilesc.mynab.finch.endpoint.AccountGroupEndpoints
object WebServer {
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Http, Service}
import com.twitter.util.Await
import io.circe.generic.auto._
import io.finch._
import io.finch.circe._
// Endpoints
val api: Service[Request, Response] = (
AccountGroupEndpoints.postGroup :+:
AccountGroupEndpoints.getGroup :+:
AccountEndpoints.getAccount :+:
AccountEndpoints.postAccount
).handle({
case e => NotFound(new Exception(e.toString))
}).toServiceAs[Application.Json]
// Service Stuff
def shutdown(): Unit = {}
def main(args: Array[String]): Unit = {
val server = Http.server.serve(":8080", api)
Await.ready(server)
shutdown()
}
}
示例7: AppService
//设置package包名称以及导入依赖的类
package io.peregrine
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Request => FinagleRequest, Response => FinagleResponse}
import com.twitter.util.{Await, Future}
class AppService(controllers: ControllerCollection)
extends Service[FinagleRequest, FinagleResponse] {
def render: ResponseBuilder = new ResponseBuilder
def apply(rawRequest: FinagleRequest): Future[FinagleResponse] = {
val adaptedRequest = RequestAdapter(rawRequest)
try {
attemptRequest(rawRequest).handle {
case t: Throwable =>
Await.result(
ErrorHandler(adaptedRequest, t, controllers)
)
}
} catch {
case e: Exception =>
ErrorHandler(adaptedRequest, e, controllers)
}
}
def attemptRequest(rawRequest: FinagleRequest): Future[FinagleResponse] = {
val adaptedRequest = RequestAdapter(rawRequest)
controllers.dispatch(rawRequest) match {
case Some(response) =>
response.asInstanceOf[Future[FinagleResponse]]
case None =>
ResponseAdapter(adaptedRequest, controllers.notFoundHandler(adaptedRequest))
}
}
}
示例8: CookieBasedSessionSpec
//设置package包名称以及导入依赖的类
package io.peregrine
import com.twitter.util.Await
class CookieBasedSessionSpec extends ShouldSpec {
"#get" should "return Some(String) if there's a value with the corresponding key" in {
val session = new CookieBasedSession("TEST_ID")
Await.result(session.put("foo", "bar"))
Await.result(session.get("foo")) should be (Some("bar"))
}
"#get" should "return None if there's a value with the corresponding key" in {
val session = new CookieBasedSession("TEST_ID")
Await.result(session.put("foo", "bar"))
Await.result(session.get("zaa")) should be (None)
}
"#set" should "set a valid value in session object" in {
val session = new CookieBasedSession("TEST_ID")
Await.result(session.put("foo", "bar"))
Await.result(session.get("foo")) should be (Some("bar"))
}
"#del" should "delete a value with the exsiting key" in {
val session = new CookieBasedSession("TEST_ID")
Await.result(session.put("foo", "bar"))
Await.result(session.get("foo")) should be (Some("bar"))
Await.result(session.del("foo"))
Await.result(session.get("foo")) should be (None)
}
}
示例9: HelloFinagleServer
//设置package包名称以及导入依赖的类
package jp.gr.java_conf.massakai.application
import com.twitter.finagle.{Http, Service, http}
import com.twitter.util.{Await, Future}
object HelloFinagleServer extends App {
val service = new Service[http.Request, http.Response] {
def apply(req: http.Request): Future[http.Response] =
Future.value(
http.Response(req.version, http.Status.Ok)
)
}
val server = Http.serve(":8080", service)
Await.ready(server)
}
示例10: HelloFinagleClient
//设置package包名称以及导入依赖的类
package jp.gr.java_conf.massakai.application
import com.twitter.finagle.{Http, Service, http}
import com.twitter.util.{Await, Future}
object HelloFinagleClient extends App {
val client: Service[http.Request, http.Response] = Http.newService("www.scala-lang.org:80")
val request = http.Request(http.Method.Get, "/")
request.host = "www.scala-lang.org"
val response: Future[http.Response] = client(request)
response.onSuccess { resp: http.Response =>
println("GET success: " + resp)
}
Await.ready(response)
}
示例11: FakeService
//设置package包名称以及导入依赖的类
package com.github.ikhoon.app.v1.fake
import javax.inject.{ Inject, Named }
import com.fasterxml.jackson.databind.JsonNode
import com.twitter.finatra.httpclient.{ HttpClient, RequestBuilder }
import com.twitter.util.{ Await, Duration, Future }
import com.typesafe.config.Config
class FakeService @Inject() (@Named("fake") httpClient: HttpClient, config: Config) {
def withSleepAsync(sec: Int): Future[JsonNode] = {
val url = s"/api/?sleep=$sec"
httpClient.executeJson[JsonNode](RequestBuilder.get(url))
}
def withSleepSync(sec: Int): JsonNode = {
val url = s"/api/?sleep=$sec"
val jsonNode = httpClient.executeJson[JsonNode](RequestBuilder.get(url))
Await.result(jsonNode, Duration.fromSeconds(100))
}
}
示例12: LoginController
//设置package包名称以及导入依赖的类
package com.example
import java.util.concurrent.TimeUnit
import com.example.db.DB
import com.twitter.finagle.http.{Cookie, Request}
import com.twitter.finatra.http.Controller
import com.twitter.finatra.request.{FormParam, QueryParam}
import com.twitter.util.Await
import scala.concurrent.duration._
class LoginController extends Controller {
post("/login") { request: Request =>
val username = request.params("loginName")
val password = request.params("loginPass")
if (username == "god" && password == "multipass") {
val f = DB.createToken(1).map { token =>
info(s"token generated: $token")
response
.ok("You are logged in! That's very cool:)")
.cookie("auth_token", token)
}
Await.result(f)
}
else response.unauthorized()
}
}
示例13: Test
//设置package包名称以及导入依赖的类
package com.github.reikje
import java.net.URL
import com.twitter.conversions.time._
import com.twitter.finagle.client.Transporter
import com.twitter.finagle.factory.TimeoutFactory
import com.twitter.finagle.http.Request
import com.twitter.finagle.service.FailFastFactory.FailFast
import com.twitter.finagle.{Http, param}
import com.twitter.io.Buf
import com.twitter.util.Await
object Test {
def main(args: Array[String]): Unit = {
val url = new URL("https://github.com")
println(s"Creating client using inet!${url.getHost}:443")
val client = Http.client
.configured(param.Label("finagle_pools"))
.configured(TimeoutFactory.Param(10.seconds))
.configured(Transporter.ConnectTimeout(10.seconds))
.configured(FailFast(enabled = false))
.withTransport.tls(hostname = url.getHost)
.withTransport.verbose
.withSessionPool.minSize(1)
.withSessionPool.maxSize(2)
.withSessionPool.maxWaiters(250)
.newClient(s"inet!${url.getHost}:443")
.toService
val request = Request("https://github.com/twitter/finagle")
val response = Await.result(client(request))
println(new String(Buf.ByteArray.Owned.extract(response.content), "UTF-8"))
}
}
示例14: ThriftMuxClient
//设置package包名称以及导入依赖的类
package com.example
import java.net.SocketAddress
import com.twitter.finagle._
import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.param.Label
import com.twitter.finagle.thrift.ThriftClientRequest
import com.twitter.util.{Await, Future}
object ThriftMuxClient {
def main(args: Array[String]) {
val futureIface = FilteredThriftMux.newIface[Hello.FutureIface]("localhost:8081")
println(Await.result(futureIface.hi()))
}
}
object FilteredThriftMux extends Client[ThriftClientRequest, Array[Byte]]
with ThriftRichClient
with Server[Array[Byte], Array[Byte]] with ThriftRichServer {
import ThriftMux._
val filter = new SimpleFilter[ThriftClientRequest, Array[Byte]] {
override def apply(request: ThriftClientRequest, service: Service[ThriftClientRequest, Array[Byte]]): Future[Array[Byte]] = {
println("Filtered")
service(request)
}
}
override def newService(dest: Name, label: String): Service[ThriftClientRequest, Array[Byte]] = {
filter andThen ThriftMux.newService(dest, label)
}
override def newClient(dest: Name, label: String): ServiceFactory[ThriftClientRequest, Array[Byte]] = ThriftMux.newClient(dest, label)
override protected def params: Stack.Params = client.params
override protected lazy val Label(defaultClientName) = Thrift.client.params[Label]
override def serve(addr: SocketAddress, service: ServiceFactory[Array[Byte], Array[Byte]]): ListeningServer = ThriftMux.serve(addr, service)
override protected val Thrift.param.ProtocolFactory(protocolFactory) = Thrift.client.params[Thrift.param.ProtocolFactory]
}
示例15: ThriftServer
//设置package包名称以及导入依赖的类
package com.example
import com.twitter.finagle.example.thriftscala.Hello
import com.twitter.finagle.example.thriftscala.Hello.Hi.{Args, Result}
import com.twitter.finagle.{Service, SimpleFilter, Thrift}
import com.twitter.util.{Await, Future}
object ThriftServer {
def main(args: Array[String]) {
val filter = new SimpleFilter[Hello.Hi.Args, Hello.Hi.Result] {
override def apply(request: Args, service: Service[Args, Result]): Future[Result] = {
println("hahaha")
service(request)
}
}
val hiService = new Service[Hello.Hi.Args, Hello.Hi.Result] {
override def apply(request: Hello.Hi.Args): Future[Hello.Hi.Result] = {
Future(Hello.Hi.Result(Some("hi!")))
}
}
val helloService = new Service[Hello.Hello.Args, Hello.Hello.Result] {
override def apply(request: Hello.Hello.Args): Future[Hello.Hello.Result] = {
Future(Hello.Hello.Result(Some("hello!")))
}
}
val serviceImpl = Hello.ServiceIface(hi = filter andThen hiService, hello = helloService)
val server = Thrift.serveIface("localhost:8081", Hello.MethodIfaceBuilder.newMethodIface(serviceImpl))
Await.ready(server)
}
}