本文整理汇总了Scala中akka.http.scaladsl.Http类的典型用法代码示例。如果您正苦于以下问题:Scala Http类的具体用法?Scala Http怎么用?Scala Http使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Http类的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: Main
//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.event.Logging
import akka.event.Logging.InfoLevel
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.google.inject.Guice
import service.documents.{DocumentService, DocumentServiceModule}
import service.health._
object Main extends App with HealthRoutes {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val settings = Settings(system)
val logger = Logging(system, getClass)
private val injector = Guice.createInjector(DocumentServiceModule)
private val docService = injector.getInstance(classOf[DocumentService])
val routes = logRequestResult("", InfoLevel)(docService.docRoutes ~ healthRoutes)
Http().bindAndHandle(routes, settings.Http.interface, settings.Http.port) map { binding =>
logger.info(s"Server started on port {}", binding.localAddress.getPort)
} recoverWith { case _ => system.terminate() }
}
示例3: StatisticDataFetcher
//设置package包名称以及导入依赖的类
package com.example
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import scala.concurrent.{ExecutionContext, Future}
class StatisticDataFetcher(implicit ec: ExecutionContext, system: ActorSystem, materializer: ActorMaterializer) extends AutoMarshaller {
val statisticsServiceUrl = {
val config = ConfigFactory.load()
config.getString("statisticsServiceUrl")
}
def getStatistics(): Future[List[StatisticData]] = {
implicit val serialization = this.serialization
implicit val formats = this.formats
val responseFuture: Future[HttpResponse] =
Http(system).singleRequest(HttpRequest(uri = statisticsServiceUrl))
responseFuture flatMap { response =>
Unmarshal(response.entity).to[StatisticsResponse] map { statisticsResponse =>
statisticsResponse.query.results.quote
}
}
}
}
示例4: Boot
//设置package包名称以及导入依赖的类
package com.saleass.app.web
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import scala.io.StdIn
object Boot extends App {
implicit val system = ActorSystem("saleass")
implicit val mat = ActorMaterializer()
implicit val ec = system.dispatcher
val route = path("hello") {
get {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Damn you av!"))
}
}
val httpBindFuture = Http().bindAndHandle(route, "localhost", 8080)
StdIn.readLine()
httpBindFuture.flatMap(_.unbind()).onComplete(_ => system.terminate())
}
示例5: 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)
}
}
示例6: WebServer
//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import scala.io.StdIn
object WebServer {
def main(args: Array[String]) {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
val route =
path("hello") {
get {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
}
}
val bindingFuture = Http().bindAndHandle(route, "0.0.0.0", 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
}
}
示例7: ExampleMain
//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.http.documenteddsl.documentation._
import akka.stream.ActorMaterializer
import scala.concurrent.Future
object ExampleMain extends App {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val routes = {
val apiRoutes = ExampleRoutes.route
val documentation = apiRoutes.selfDescribe(Documentation())
val documentationRoute = pathPrefix("api.json") {
DocumentationRoutes(documentation)
}
apiRoutes ~ documentationRoute
}
for {
port <- Http().bindAndHandle(routes, "localhost", 8080)
_ <- Future {
println(
s"""Example App is available at http://localhost:8080
|
|You can try ExampleResource at
| GET http://localhost:8080/resources
| GET http://localhost:8080/resources/x
| POST http://localhost:8080/resources {"name": "new resource"}
| PUT http://localhost:8080/resources/x {"name": "updated name"}
| DELETE http://localhost:8080/resources/x
|
|Api Documentation (Json) is available at
| OPTIONS http://localhost:8080/api.json // api toc
| GET http://localhost:8080/api.json // full api
| GET http://localhost:8080/api.json/x // specified api route
|
|Press RETURN to stop...
""".stripMargin)
io.StdIn.readLine()
}
_ <- port.unbind()
} { system.terminate() }
}
示例8: AService
//设置package包名称以及导入依赖的类
package service.a.app
import scala.concurrent.ExecutionContext
import scala.io.StdIn
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport.defaultNodeSeqMarshaller
import akka.http.scaladsl.marshalling.ToResponseMarshallable.apply
import akka.http.scaladsl.server.Directive.addByNameNullaryApply
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.RouteResult.route2HandlerFlow
import akka.stream.ActorMaterializer
import service.a.core.ACoreBooted
object AService extends App with ACoreBooted with AConfig {
protected implicit val executor: ExecutionContext = system.dispatcher
protected implicit val materializer: ActorMaterializer = ActorMaterializer()
val route =
path("hello") {
get {
complete {
<h1>Say hello to akka-http</h1>
}
}
} ~
path("dude") {
get {
complete {
<h1>Say hello to dude</h1>
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", port.toInt)
println(s"Server online at http://localhost:11011/\nPress RETURN to stop...")
StdIn.readLine()
bindingFuture
.flatMap(_.unbind())
.onComplete { _ => system.terminate() }
}
示例9: Server
//设置package包名称以及导入依赖的类
package org.goingok.httpServer
import akka.http.scaladsl.Http
import org.goingok.BuildInfo
import org.goingok.data.persistence.db.DatabaseOps
import scala.util.{Failure, Success}
object Server extends GoingOkAPI {
import org.goingok.GoingOkContext._
var dbOk = false
def startServer(address:String, port:Int) = {
log.info("->> STARTING {} - version {} <<-",BuildInfo.name,BuildInfo.version)
log.info("Connecting to DB server")
connectDb
log.info("Starting http server at {}:{}",address,port)
Http().bindAndHandle(routes,address,port)
}
def connectDb: Unit = {
DatabaseOps.version.onComplete {
case Success(result:String) => {
dbOk = true
log.info("Current version is: "+result)
// Create tables that don't exist
DatabaseOps.checkAndCreateTables()
// Get the number of rows for all tables
val tableRows = DatabaseOps.tableSizes()
if(tableRows.isLeft) tableRows.left.map(i => log.info("Database tables exist: {}",i))
else log.error("There was a problem with accessing the database tables")
}
case Failure(e:Exception) => log.error("Could not get version from db: "+e.getMessage)
case _ => log.error("There was a problem getting the version from the database")
}
}
}
示例10: 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)
}
示例11: DynamoClientImpl
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.dynamodb.impl
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.MediaType.NotCompressible
import akka.http.scaladsl.model.{ContentType, MediaType}
import akka.stream.Materializer
import akka.stream.alpakka.dynamodb.AwsOp
import akka.stream.alpakka.dynamodb.impl.AwsClient.{AwsConnect, AwsRequestMetadata}
import akka.stream.scaladsl.{Sink, Source}
import com.amazonaws.AmazonServiceException
import com.amazonaws.http.HttpResponseHandler
class DynamoClientImpl(
val settings: DynamoSettings,
val errorResponseHandler: HttpResponseHandler[AmazonServiceException]
)(implicit protected val system: ActorSystem, implicit protected val materializer: Materializer)
extends AwsClient[DynamoSettings] {
override protected val service = "dynamodb"
override protected val defaultContentType =
ContentType.Binary(MediaType.customBinary("application", "x-amz-json-1.0", NotCompressible))
override protected implicit val ec = system.dispatcher
override protected val connection: AwsConnect =
if (settings.port == 443)
Http().cachedHostConnectionPoolHttps[AwsRequestMetadata](settings.host)(materializer)
else
Http().cachedHostConnectionPool[AwsRequestMetadata](settings.host, settings.port)(materializer)
def single(op: AwsOp) = Source.single(op).via(flow).map(_.asInstanceOf[op.B]).runWith(Sink.head)
}
示例12: MagdaApp
//设置package包名称以及导入依赖的类
package au.csiro.data61.magda
import akka.actor.{ Actor, ActorLogging, ActorSystem, DeadLetter, Props }
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import au.csiro.data61.magda.api.SearchApi
import au.csiro.data61.magda.search.elasticsearch.{ DefaultClientProvider, ElasticSearchQueryer }
object MagdaApp extends App {
implicit val config = AppConfig.conf()
implicit val system = ActorSystem("search-api", config)
implicit val executor = system.dispatcher
implicit val materializer = ActorMaterializer()
implicit val clientProvider = new DefaultClientProvider
implicit val logger = Logging(system, getClass)
logger.info("Starting API in env {} on port {}", AppConfig.getEnv, config.getString("http.port"))
val listener = system.actorOf(Props(classOf[Listener]))
system.eventStream.subscribe(listener, classOf[DeadLetter])
logger.debug("Starting API")
val searchQueryer = ElasticSearchQueryer.apply
val api = new SearchApi(searchQueryer)
val interface = Option(System.getenv("npm_package_config_interface")).orElse(Option(config.getString("http.interface"))).getOrElse("127.0.0.1")
val port = Option(System.getenv("npm_package_config_port")).map(_.toInt).orElse(Option(config.getInt("http.port"))).getOrElse(6101)
Http().bindAndHandle(api.routes, interface, port)
}
class Listener extends Actor with ActorLogging {
def receive = {
case d: DeadLetter => log.debug(d.message.toString())
}
}
示例13: Main
//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import bot.application.EchoLineBot
import bot.line.client.{ReplyMessageClient, SignatureVerifier}
import com.typesafe.config.ConfigFactory
object Main extends App {
implicit val system = ActorSystem("LINE-bot")
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
val config = ConfigFactory.load()
val bot = new EchoLineBot(
channelSecret = config.getString("bot.line.channelSecret"),
signatureVerifier = new SignatureVerifier,
messageReplier = new ReplyMessageClient(config.getString("bot.line.accessToken"))
)
Http().bindAndHandle(bot.routes, config.getString("http.interface"), config.getInt("http.port"))
}
示例14: RestService
//设置package包名称以及导入依赖的类
package com.github.btesila.weather.monitor
import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives.{complete => _, get => _, handleExceptions => _, path => _, _}
import akka.http.scaladsl.server.directives.ExecutionDirectives._
import akka.http.scaladsl.server.directives.MethodDirectives._
import akka.http.scaladsl.server.directives.PathDirectives._
import akka.http.scaladsl.server.directives.RouteDirectives._
import akka.stream.ActorMaterializer
import com.github.btesila.weather.monitor.routes.WeatherMonitorRoutes
import scala.concurrent.Future
class RestService()(implicit system: ActorSystem, mat: ActorMaterializer) {
val ping = (path("ping") & get) {
complete("OK")
}
val routes = WeatherMonitorRoutes(WeatherMonitorOps()).routes
def start(): Future[Http.ServerBinding] = {
val handler = logRequestResult("req/resp", Logging.DebugLevel) {
handleExceptions(Fault.Handler) {
ping ~ routes
}
}
val httpSettings = Settings(system).WeatherMonitor.Acceptor
Http().bindAndHandle(
handler = handler,
interface = httpSettings.Host,
port = httpSettings.Port
)
}
}
object RestService {
def apply()(implicit system: ActorSystem, mat: ActorMaterializer) = new RestService()
}
示例15: Main
//设置package包名称以及导入依赖的类
package com.noedominguez.class_orchestration.restapi
import com.noedominguez.class_orchestration.restapi.services.{AuthService, TeamsService, UsersService, ExplorationsService, ExplorationEventsService, ExplorationObjectsService}
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.noedominguez.class_orchestration.restapi.http.HttpService
import com.noedominguez.class_orchestration.restapi.utils.{DatabaseService, FlywayService}
import com.noedominguez.class_orchestration.restapi.utils.Config
import scala.concurrent.ExecutionContext
object Main extends App with Config {
implicit val actorSystem = ActorSystem()
implicit val executor: ExecutionContext = actorSystem.dispatcher
implicit val log: LoggingAdapter = Logging(actorSystem, getClass)
implicit val materializer: ActorMaterializer = ActorMaterializer()
val flywayService = new FlywayService(jdbcUrl, dbUser, dbPassword)
flywayService.migrateDatabaseSchema
val databaseService = new DatabaseService(jdbcUrl, dbUser, dbPassword)
val usersService = new UsersService(databaseService)
val authService = new AuthService(databaseService)(usersService)
val teamsService= new TeamsService(databaseService)
val explorationsService= new ExplorationsService(databaseService)
val explorationEventsService= new ExplorationEventsService(databaseService)
val explorationObjectsService= new ExplorationObjectsService(databaseService)
val httpService = new HttpService(usersService, authService, teamsService, explorationsService, explorationEventsService,explorationObjectsService)
Http().bindAndHandle(httpService.routes, httpHost, httpPort)
}