本文整理汇总了Scala中com.twitter.finagle.Http类的典型用法代码示例。如果您正苦于以下问题:Scala Http类的具体用法?Scala Http怎么用?Scala Http使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Http类的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: MockClient
//设置package包名称以及导入依赖的类
package featherbed
import java.net.URL
import com.twitter.finagle.{Filter, Http}
import com.twitter.finagle.http.{Request, Response}
import org.scalamock.matchers.Matcher
import org.scalamock.scalatest.MockFactory
package object fixture {
private[fixture] class MockClient (
baseUrl: URL,
filter: Filter[Request, Response, Request, Response]
) extends Client(baseUrl) {
override def clientTransform(c: Http.Client) = c.filtered(filter)
}
trait ClientTest { self: MockFactory =>
class TransportRequestMatcher(f: Request => Unit) extends Matcher[Any] {
override def canEqual(x: Any) = x match {
case x: Request => true
case _ => false
}
override def safeEquals(that: Any): Boolean = that match {
case x: Request => f(x); true
case _ => false
}
}
def request(f: Request => Unit): TransportRequestMatcher = new TransportRequestMatcher(f)
def mockClient(url: String, filter: Filter[Request, Response, Request, Response]): Client =
new MockClient(new URL(url), filter)
}
}
示例5: HttpTips
//设置package包名称以及导入依赖的类
package com.bob.scalatour.twitters
import com.twitter.finagle.transport.Transport
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http.{Method, Response, Request}
import com.twitter.finagle.loadbalancer.{Balancers, LoadBalancerFactory}
import com.twitter.util.{Await => twitterAwait, Monitor}
object HttpTips {
def main(args: Array[String]) {
val balancer: LoadBalancerFactory = Balancers.heap()
val monitor: Monitor = new Monitor {
override def handle(exc: Throwable): Boolean = {
// do sth with the exception
true
}
}
val client: Service[Request, Response] = Http.client
.withMonitor(monitor)
.withLoadBalancer(balancer)
// It’s important to disable Fail Fast when only have one host in the replica set
// because Finagle doesn’t have any other path to choose.
.withSessionQualifier.noFailFast
.configured(Transport.Options(noDelay = false, reuseAddr = false))
.newService("172.16.40.68:8090,172.16.40.69:8090", "riskservice")
val request = Request(Method.Get, "/calculator/users/together?userId=1234&date=2015-12-12&bbb=bbb")
// here we should set the host header value even it is empty,otherwise it will nothing can obtain
request.headerMap.add("host", "")
(1 to 20).map {
z => {
println(s"now is the ${z} request to send")
val response = client(request)
twitterAwait.ready(response.map(x => println(x.contentString)))
}
}
val url = Request.queryString("/calculator/users/together", Map("userId" -> "314", "date" -> "2015", "bbb" -> "bbb"))
println(url) // url value will be: /calculator/users/together?userId=314&date=2015&bbb=bbb
println("http invoke done")
}
}
示例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: 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)
}
示例8: 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)
}
示例9: 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"))
}
}
示例10: TestClientServerMain
//设置package包名称以及导入依赖的类
package com.sgtest
import java.net.InetSocketAddress
import com.sgtest.controllers.AuthenticationController
import com.twitter.finagle.Http
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.stats.DefaultStatsReceiver
import com.twitter.finagle.zipkin.thrift.ZipkinTracer
import com.twitter.finatra.http.HttpServer
import com.twitter.finatra.http.filters.{CommonFilters, LoggingMDCFilter, TraceIdMDCFilter}
import com.twitter.finatra.http.routing.HttpRouter
object TestClientServerMain extends TestClientServer
class TestClientServer extends HttpServer {
override def defaultFinatraHttpPort = ":8888"
override val adminPort = flag("admin.port", new InetSocketAddress(8880), "Admin Http server port")
override def configureHttp(router: HttpRouter) {
router
.filter[LoggingMDCFilter[Request, Response]]
.filter[TraceIdMDCFilter[Request, Response]]
.filter[CommonFilters]
.add[AuthenticationController]
}
override def configureHttpServer(server: Http.Server): Http.Server = {
val receiver = DefaultStatsReceiver.get
val zipkinHost = sys.env.getOrElse("SG_ZIPKIN_HOST","localhost")
val zipkinPort = sys.env.getOrElse("SG_ZIPKIN_PORT", "9410").toInt
val tracer = ZipkinTracer.mk(
host = zipkinHost,
port = zipkinPort,
statsReceiver = receiver
)
server
.withTracer(tracer)
.withLabel("test-client-server")
}
}
示例11: Bucket
//设置package包名称以及导入依赖的类
package io.github.daviddenton.finagle.aws
import java.net.URI
import java.time.Clock
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Http, Service}
case class Bucket(name: String) extends AnyVal {
def toUri = URI.create(s"https://$name.s3.amazonaws.com")
}
object Bucket {
def client(bucket: Bucket, region: AwsRegion, credentials: AwsCredentials,
clock: Clock = Clock.systemUTC()): Service[Request, Response] = {
val signatureV4Signer = AwsSignatureV4Signer(AwsCredentialScope(region, AwsService("s3")), credentials)
val authority = bucket.toUri.getAuthority
val http = Http.client.withTls(authority)
.newService(s"$authority:443")
AwsCredentialFilter(authority, clock, signatureV4Signer)
.andThen(http)
}
}
示例12: Yahoo
//设置package包名称以及导入依赖的类
package stockTicker
import java.io.{BufferedReader, InputStreamReader}
import java.time.LocalDate
import com.twitter.bijection.Conversion.asMethod
import com.twitter.finagle.http.Response
import com.twitter.finagle.service.{Backoff, RetryBudget}
import com.twitter.finagle.{Http, http}
import com.twitter.util.TimeConversions._
import com.twitter.util.{Await, Future}
import scala.collection.immutable.Seq
object Yahoo {
private def rootUri = "real-chart.finance.yahoo.com"
def pricesURL(businessDate : java.time.LocalDate, ticker: String) : String = {
val lastYear = businessDate.minusYears(1)
val url =f"http://$rootUri/table.csv?s=$ticker&a=${lastYear.getMonthValue}&b=${lastYear.getDayOfMonth}&c=${lastYear.getYear}&d=${businessDate.getMonthValue}&e=${businessDate.getDayOfMonth}&f=${businessDate.getYear}&g=d&ignore=.csv"
url
}
private val budget: RetryBudget = RetryBudget(
ttl = 10.seconds,
minRetriesPerSec = 5,
percentCanRetry = 0.1
)
private val client = Http.client
.withRetryBudget(budget)
.withRetryBackoff(Backoff.const(10 seconds))
.newService(s"$rootUri:80")
implicit val priceSource = new PriceSource[StockPrice] {
override def fetchPrices(ticker: String) : Seq[StockPrice] = {
val request = http.Request(http.Method.Get, pricesURL(LocalDate.now, ticker))
request.host = rootUri
val response = client(request).as[Future[Response]]
Await.result(response map { res =>
val reader = new BufferedReader(new InputStreamReader(res.getInputStream))
reader.readLine()
Stream.continually(reader.readLine())
.takeWhile(s=> s!= null && !s.isEmpty)
.map { StockPrice(ticker, _) }
})
}
}
}
示例13: UserService
//设置package包名称以及导入依赖的类
package net.gutefrage.finch.services
import io.catbird.util._
import cats.data.EitherT
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http.{Request, Response}
import com.twitter.util.Future
import io.circe.parser.parse
import io.circe.generic.auto._
import net.gutefrage.finch.models.User
class UserService {
private case class RandomUserResults(results: List[User])
private val hostname = "randomuser.me"
private val client: Service[Request, Response] =
Http.client.withTls(hostname).newService(s"$hostname:443")
def get(): Future[List[User]] = {
val req = Request("/api/", "results" -> "10")
req.host = "api.randomuser.me"
req.contentType = "application/json"
(for {
response <- EitherT.right(client(req))
rawJson <- EitherT
.fromEither[Future](parse(response.contentString))
.leftMap(_ => List.empty[User])
user <- EitherT
.fromEither[Future](rawJson.as[RandomUserResults])
.leftMap(_ => List.empty[User])
} yield user.results).merge
}
}
示例14: Server
//设置package包名称以及导入依赖的类
package com.slouc.finchdemo.http.server
import com.slouc.finchdemo.http.api.Api
import com.twitter.finagle.http.{Request, Response}
import com.twitter.server._
import com.twitter.finagle.{Http, Service}
import com.twitter.util.Await
import io.circe.generic.auto._
import io.finch.circe._
object Server extends TwitterServer {
val api: Service[Request, Response] =
(Api.endpoint1 :+: Api.endpoint2 :+: Api.endpoint3 :+: Api.endpoint4)
.toService
def main(): Unit = {
val server = Http.server.serve(":8080", api)
onExit {
server.close()
}
Await.ready(adminHttpServer)
}
}
示例15: Http2StreamingTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle.http2
import com.twitter.finagle.Http
import com.twitter.finagle.Http.HttpImpl
import com.twitter.finagle.http.AbstractStreamingTest
import com.twitter.finagle.http2.param.PriorKnowledge
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class Http2StreamingTest extends AbstractStreamingTest {
def impl: HttpImpl = Http2
override def configureClient: Http.Client => Http.Client = { client =>
client.configured(PriorKnowledge(true))
}
override def configureServer: Http.Server => Http.Server = { server =>
server.configured(PriorKnowledge(true))
}
}