本文整理汇总了Scala中akka.http.scaladsl.Http.ServerBinding类的典型用法代码示例。如果您正苦于以下问题:Scala ServerBinding类的具体用法?Scala ServerBinding怎么用?Scala ServerBinding使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ServerBinding类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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)
}
}
示例2: ForwarderActor
//设置package包名称以及导入依赖的类
import akka.actor.{Actor, ActorSystem, Props}
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.{IncomingConnection, ServerBinding}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers._
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import org.apache.spark.streaming.receiver.ActorHelper
import org.apache.spark._
import org.apache.spark.streaming._
import scala.concurrent.Future
class ForwarderActor extends Actor with ActorHelper {
def receive = {
case data: String => store(data)
}
}
object Main extends App {
implicit val system = ActorSystem("sparkDriverActorSystem")
implicit val mat = ActorMaterializer()
implicit val ec = system.dispatcher
val host = "localhost"
val restPort = 9090
val actorName = "forwarder"
val sparkDriverPort = 7777
// Spark Streaming
val conf = new SparkConf().setMaster("local[*]").setAppName("TestWebApp").set("spark.driver.port", sparkDriverPort.toString).set("spark.driver.host", host).set("spark.akka.heartbeat.interval", "1s")
val ssc = new StreamingContext(conf, Seconds(30))
ssc.actorStream[String](Props[ForwarderActor], actorName).print()
// Akka HTTP
val restSource: Source[IncomingConnection, Future[ServerBinding]] = Http().bind(interface = host, port = restPort)
val handler: HttpRequest => HttpResponse = {
case HttpRequest(GET, Uri.Path("/"), _, _, _) =>
HttpResponse(entity = HttpEntity(ContentTypes.`text/html(UTF-8)`, "<html><body>Hi there!</body></html>"))
case HttpRequest(POST, Uri.Path("/data"), _, entity, _) if entity.contentType == ContentTypes.`application/json` => {
val url: String = s"akka.tcp://[email protected]$host:${sparkDriverPort + 1}/user/Supervisor0/$actorName"
val s: Future[String] = Unmarshal(entity).to[String]
s foreach (system.actorSelection(url) ! _)
HttpResponse(200)
}
case _: HttpRequest =>
HttpResponse(404, entity = "Page not found!")
}
// Start all the things
ssc.start()
val binding: Future[ServerBinding] = restSource.to(Sink.foreach { _ handleWithSyncHandler handler }).run()
}
示例3: Main
//设置package包名称以及导入依赖的类
package com.fingerco
import scala.concurrent.Future
import akka.actor.{ ActorSystem, Actor, Props }
import akka.event.Logging
import akka.util.Timeout
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.typesafe.config.{ Config, ConfigFactory }
object Main extends App
with RequestTimeout {
val config = ConfigFactory.load()
val host = config.getString("http.host")
val port = config.getInt("http.port")
implicit val system = ActorSystem()
implicit val ec = system.dispatcher
val api = new RestApi(system, requestTimeout(config)).routes
implicit val materializer = ActorMaterializer()
val bindingFuture: Future[ServerBinding] =
Http().bindAndHandle(api, host, port)
}
trait RequestTimeout {
import scala.concurrent.duration._
def requestTimeout(config: Config): Timeout = {
val t = config.getString("akka.http.server.request-timeout")
val d = Duration(t)
FiniteDuration(d.length, d.unit)
}
}
示例4: AdminHttpService
//设置package包名称以及导入依赖的类
package csw.apps.clusterseed.admin.http
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import csw.apps.clusterseed.admin.internal.{ActorRuntime, Settings}
import csw.apps.clusterseed.commons.ClusterSeedLogger
import csw.services.location.commons.ClusterAwareSettings
import scala.async.Async._
import scala.concurrent.Future
import scala.util.control.NonFatal
class AdminHttpService(adminRoutes: AdminRoutes, actorRuntime: ActorRuntime, settings: Settings)
extends ClusterSeedLogger.Simple {
import actorRuntime._
lazy val registeredLazyBinding: Future[ServerBinding] = async {
val binding = await(bind())
log.info(s"Server online at http://${binding.localAddress.getHostName}:${binding.localAddress.getPort}/")
binding
} recoverWith {
case NonFatal(ex) ?
log.error("can not start admin http server", ex = ex)
shutdown().map(_ ? throw ex)
}
private def bind() = Http().bindAndHandle(
handler = adminRoutes.route,
interface = ClusterAwareSettings.hostname,
port = settings.`admin-port`
)
}
示例5: HmdaFilingApi
//设置package包名称以及导入依赖的类
package hmda.api
import akka.actor.{ ActorSystem, Props }
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.pattern.pipe
import akka.stream.ActorMaterializer
import akka.util.Timeout
import hmda.api.http.{ BaseHttpApi, HmdaCustomDirectives, InstitutionsHttpApi, LarHttpApi }
import hmda.api.HmdaConfig._
import scala.concurrent.duration._
import scala.concurrent.{ ExecutionContext, Future }
object HmdaFilingApi {
def props(): Props = Props(new HmdaFilingApi)
}
class HmdaFilingApi
extends HttpApi
with BaseHttpApi
with LarHttpApi
with InstitutionsHttpApi
with HmdaCustomDirectives {
implicit val flowParallelism = configuration.getInt("hmda.actor-flow-parallelism")
override val name = "hmda-filing-api"
lazy val httpTimeout = configuration.getInt("hmda.http.timeout")
implicit val timeout = Timeout(httpTimeout.seconds)
override lazy val host = configuration.getString("hmda.http.host")
override lazy val port = configuration.getInt("hmda.http.port")
implicit val system: ActorSystem = context.system
override implicit val materializer: ActorMaterializer = ActorMaterializer()
implicit val ec: ExecutionContext = context.dispatcher
override val log = Logging(system, getClass)
val paths: Route = routes(s"$name") ~ larRoutes ~ institutionsRoutes
override val http: Future[ServerBinding] = Http(system).bindAndHandle(
paths,
host,
port
)
http pipeTo self
}
示例6: HmdaAdminApi
//设置package包名称以及导入依赖的类
package hmda.api
import akka.actor.{ ActorSystem, Props }
import akka.event.Logging
import akka.pattern.pipe
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import hmda.api.http.BaseHttpApi
import hmda.api.http.admin.InstitutionAdminHttpApi
import scala.concurrent.duration._
import scala.concurrent.{ ExecutionContext, Future }
object HmdaAdminApi {
def props(): Props = Props(new HmdaAdminApi)
}
class HmdaAdminApi extends HttpApi with BaseHttpApi with InstitutionAdminHttpApi {
val config = ConfigFactory.load()
lazy val httpTimeout = config.getInt("hmda.http.timeout")
override implicit val timeout = Timeout(httpTimeout.seconds)
override val name = "hmda-admin-api"
override val host: String = config.getString("hmda.http.adminHost")
override val port: Int = config.getInt("hmda.http.adminPort")
override implicit val system: ActorSystem = context.system
override implicit val materializer: ActorMaterializer = ActorMaterializer()
override implicit val ec: ExecutionContext = context.dispatcher
override val log = Logging(system, getClass)
override val paths: Route = routes(s"$name") ~ institutionAdminRoutes
override val http: Future[ServerBinding] = Http(system).bindAndHandle(
paths,
host,
port
)
http pipeTo self
}
示例7: Manager
//设置package包名称以及导入依赖的类
package reactivehub.akka.stream.apns.manager
import akka.actor.{ActorRef, ActorSystem}
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.kafka.ProducerSettings
import akka.stream.ActorMaterializer
import akka.util.Timeout
import reactivehub.akka.stream.apns.pusher._
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.io.StdIn
import scala.util.Success
import slick.driver.H2Driver.api._
object Manager extends RestApi {
val dbConfig = "h2"
val kafka = "192.168.99.100:9092"
val topic = "notifications"
val interface = "0.0.0.0"
val port = 8080
implicit val system = ActorSystem("system")
implicit val materializer = ActorMaterializer()
implicit val dispatcher = system.dispatcher
implicit val timeout = Timeout(10.second)
def main(args: Array[String]): Unit = {
val binding = createService().flatMap(manager => bind(manager))
binding.onComplete {
case Success(b) =>
println(s"Successfully bound to ${b.localAddress}, press enter to exit")
case _ =>
println("Failed to bootstrap Manager, press enter")
}
StdIn.readLine()
binding.flatMap(_.unbind()).onComplete(_ => system.terminate())
}
private def createService(): Future[ActorRef] = {
val db = Database.forConfig(dbConfig)
val store = new SqlDeviceStore(db)
val queue = new KafkaPushQueue(topic, producerSettings)
db.run(devices.schema.drop)
.recover({ case _ => () })
.flatMap(_ => db.run(devices.schema.create))
.map(_ => system.actorOf(DeviceService.props(store, queue)))
}
private def bind(service: ActorRef): Future[ServerBinding] =
Http(system).bindAndHandle(route(service), interface, port)
private def producerSettings: ProducerSettings[Long, PushData] =
ProducerSettings(system, ScalaLongSerializer, PushDataSerializer)
.withBootstrapServers(kafka)
}
示例8: startService
//设置package包名称以及导入依赖的类
package com.wincom.dcim.rest
import akka.actor.{ActorRef, ActorSystem}
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.Config
import scala.concurrent.Future
trait WebServer extends RequestTimeout {
def startService(shardedFsus: ActorRef)(implicit system: ActorSystem) = {
val config = system.settings.config
val settings = Settings(system)
val host = settings.http.host
val port = settings.http.port
implicit val ec = system.dispatcher
val api = new FsuService(shardedFsus, system, requestTimeout(config)).routes
implicit val materializer = ActorMaterializer()
val bindingFuture: Future[ServerBinding] =
Http().bindAndHandle(api, host, port)
val log = Logging(system.eventStream, "sharded-fsus")
bindingFuture.map { serverBinding =>
log.info(s"Sharded FSU API bound to ${serverBinding.localAddress} ")
}.onFailure {
case ex: Exception =>
log.error(ex, "Failed to bind to {}:{}!", host, port)
system.terminate()
}
}
}
trait RequestTimeout {
import scala.concurrent.duration._
def requestTimeout(config: Config): Timeout = {
val t = config.getString("akka.http.server.request-timeout")
val d = Duration(t)
FiniteDuration(d.length, d.unit)
}
}
示例9: Api
//设置package包名称以及导入依赖的类
package api
import java.util.concurrent.TimeUnit
import akka.actor.{Actor, ActorLogging, Props}
import akka.event.LoggingReceive
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.stream.ActorMaterializer
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{Await, Future}
class Api() extends Actor with ActorLogging with ApiRoutes {
import context.dispatcher
implicit val system = context.system
implicit val materializer = ActorMaterializer()
log.info("Api up and running...")
val binding: Future[ServerBinding] = Http().bindAndHandle(routes, "0.0.0.0", 8080)
binding.onFailure {
case ex: Exception =>
log.error(ex, "Failed to bind to {}:{}!", "0.0.0.0", 8080)
}
override def postStop(): Unit = {
log.info("Stopping api...")
Await.result(binding.map(_.unbind()), FiniteDuration(30, TimeUnit.SECONDS))
}
def receive: Receive = LoggingReceive {
case a => log.warning("Unknown message")
}
}
object Api {
def name: String = "api"
def props(): Props = {
Props(
classOf[Api]
)
}
}
示例10: HttpApi
//设置package包名称以及导入依赖的类
package api.http
import java.net.InetSocketAddress
import akka.actor.{ Actor, ActorSystem, Status }
import akka.event.LoggingAdapter
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import scala.concurrent.{ ExecutionContext, Future }
abstract class HttpApi extends Actor {
val log: LoggingAdapter
val path = self.path
val name: String
val host: String
val port: Int
implicit val system: ActorSystem
implicit val materializer: ActorMaterializer
implicit val ec: ExecutionContext
val paths: Route
val http: Future[ServerBinding]
override def preStart(): Unit = {
super.preStart()
log.info(s"Started $path")
}
override def postStop(): Unit = {
super.postStop()
log.info(s"Stopped $path")
}
override def receive: Receive = {
case Http.ServerBinding(s) => handleServerBinding(s)
case Status.Failure(e) => handleBindFailure(e)
}
private def handleServerBinding(address: InetSocketAddress): Unit = {
log.info(s"$name started on {}", address)
context.become(Actor.emptyBehavior)
}
private def handleBindFailure(error: Throwable): Unit = {
log.error(s"Failed to bind to $host:$port")
context stop self
}
}
示例11: NotificationsApp
//设置package包名称以及导入依赖的类
package it.wknd.reactive.backend
import akka.actor.{ActorSystem, Props}
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.stream.ActorMaterializer
import akka.stream.actor.ActorPublisher
import akka.stream.scaladsl.{RunnableGraph, Sink, Source}
import com.softwaremill.macwire.wire
import com.typesafe.config.ConfigFactory
import it.wknd.reactive.backend.flow.EventGraph
import it.wknd.reactive.backend.model.{HealthNotification, HeartRate, Step}
import it.wknd.reactive.backend.source.{HrActorSource, SourceProvider, StepActorSource}
import scala.concurrent.Future
object NotificationsApp extends App {
implicit val config = ConfigFactory.load()
implicit val actorSystem = ActorSystem("hr-backend")
implicit val ec = actorSystem.dispatcher
implicit val materializer = ActorMaterializer()
lazy val sourceProvider = wire[SourceProvider]
val hrActor = actorSystem.actorOf(Props[HrActorSource])
val hrPub = ActorPublisher[HeartRate](hrActor)
val stepActor = actorSystem.actorOf(Props[StepActorSource])
val stepPub = ActorPublisher[Step](stepActor)
RunnableGraph fromGraph {
EventGraph(
stepSource = Source.fromPublisher(stepPub),
hrSource = Source.fromPublisher(hrPub),
sink = Sink.actorSubscriber[HealthNotification](Props[NotifierActor]))
} run()
val bindingFuture: Future[ServerBinding] =
Http().bindAndHandle(sourceProvider.routes(hrActor = hrActor, stepActor = stepActor), "localhost", 2525)
}
示例12: Main
//设置package包名称以及导入依赖的类
package com.jordimasip
import scala.concurrent.Future
import akka.actor.{ ActorSystem , Actor , Props }
import akka.event.Logging
import akka.util.Timeout
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.typesafe.config.{ Config, ConfigFactory }
object Main extends App with RequestTimeout {
val config = ConfigFactory.load()
val host = config.getString("http.host")
val port = config.getInt("http.port")
implicit val system = ActorSystem()
implicit val ec = system.dispatcher
val api = new RestApi(system, requestTimeout(config)).routes
implicit val materializer = ActorMaterializer()
val bindingFuture: Future[ServerBinding] = Http().bindAndHandle(api, host, port)
val log = Logging(system.eventStream, "go-tickets")
bindingFuture.map { serverBinding =>
log.info(s"RestApi bound to ${serverBinding.localAddress} ")
}.onFailure {
case ex: Exception =>
log.error(ex, "Failed to bind to {}:{}!", host, port)
system.terminate()
}
}
trait RequestTimeout {
import scala.concurrent.duration._
def requestTimeout(config: Config): Timeout = {
val t = config.getString("akka.http.server.request-timeout")
val d = Duration(t)
FiniteDuration(d.length, d.unit)
}
}
示例13: startup
//设置package包名称以及导入依赖的类
package com.jordimasip
import scala.concurrent.Future
import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
trait Startup extends RequestTimeout {
def startup(api: Route)(implicit system: ActorSystem) = {
val host = system.settings.config.getString("http.host") // Gets the host and a port from the configuration
val port = system.settings.config.getInt("http.port")
startHttpServer(api, host, port)
}
def startHttpServer(api: Route, host: String, port: Int)
(implicit system: ActorSystem) = {
implicit val ec = system.dispatcher //bindAndHandle requires an implicit ExecutionContext
implicit val materializer = ActorMaterializer()
val bindingFuture: Future[ServerBinding] =
Http().bindAndHandle(api, host, port) //Starts the HTTP server
val log = Logging(system.eventStream, "go-ticks")
bindingFuture.map { serverBinding =>
log.info(s"RestApi bound to ${serverBinding.localAddress} ")
}.onFailure {
case ex: Exception =>
log.error(ex, "Failed to bind to {}:{}!", host, port)
system.terminate()
}
}
}
示例14: RestApiServer
//设置package包名称以及导入依赖的类
package com.spr.akka
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.stream.Materializer
import com.typesafe.config.ConfigFactory
import scala.concurrent.Future
class RestApiServer(api: RestApi)(implicit system: ActorSystem, materializer: Materializer) {
def bind(): Future[ServerBinding] = {
val config = ConfigFactory.load()
val host = config.getString("http.host")
val port = config.getInt("http.port")
implicit val system = this.system
implicit val materializer = this.materializer
Http().bindAndHandle(api.route, host, port)
}
}
示例15: Api
//设置package包名称以及导入依赖的类
package nl.tradecloud.user
import java.util.concurrent.TimeUnit
import akka.actor.{Actor, ActorLogging, Props}
import akka.event.LoggingReceive
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.stream.ActorMaterializer
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{Await, Future}
class Api() extends Actor with ActorLogging with ApiRoutes {
import context.dispatcher
implicit val system = context.system
implicit val materializer = ActorMaterializer()
log.info("User api up and running...")
val binding: Future[ServerBinding] = Http().bindAndHandle(routes, "0.0.0.0", 8080)
binding.onFailure {
case ex: Exception =>
log.error(ex, "Failed to bind to {}:{}!", "0.0.0.0", 8080)
}
override def postStop(): Unit = {
log.info("Stopping api...")
Await.result(binding.map(_.unbind()), FiniteDuration(30, TimeUnit.SECONDS))
}
def receive: Receive = LoggingReceive {
case a => log.warning("Unknown message")
}
}
object Api {
final val name: String = "api"
def props(): Props = {
Props(
classOf[Api]
)
}
}