本文整理汇总了Scala中akka.http.scaladsl.Http类的典型用法代码示例。如果您正苦于以下问题:Scala Http类的具体用法?Scala Http怎么用?Scala Http使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Http类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
}
开发者ID:divanvisagie,项目名称:vote,代码行数:29,代码来源:Boot.scala
示例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() }
}
开发者ID:devknutst,项目名称:watermarkAkka,代码行数:30,代码来源:Main.scala
示例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
}
}
}
}
开发者ID:frossi85,项目名称:financial-statistics-crawler,代码行数:32,代码来源:StatisticDataFetcher.scala
示例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())
}
开发者ID:arinal,项目名称:saleass,代码行数:25,代码来源:Boot.scala
示例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)
}
}
开发者ID:topaztechnology,项目名称:eventstore,代码行数:50,代码来源:WebService.scala
示例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
}
}
开发者ID:artyomboyko,项目名称:death-star-design,代码行数:31,代码来源:WebServer.scala
示例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() }
}
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:51,代码来源:ExampleMain.scala
示例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() }
}
开发者ID:kevinkl,项目名称:scalakka,代码行数:46,代码来源:AService.scala
示例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")
}
}
}
开发者ID:GoingOK,项目名称:goingok-server,代码行数:42,代码来源:Server.scala
示例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)
}
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:56,代码来源:HttpClientAsActor.scala
示例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)
}
开发者ID:akka,项目名称:alpakka,代码行数:34,代码来源:DynamoClientImpl.scala
示例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())
}
}
开发者ID:TerriaJS,项目名称:magda,代码行数:39,代码来源:MagdaApp.scala
示例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"))
}
开发者ID:xoyo24,项目名称:akka-http-line-bot,代码行数:23,代码来源:Main.scala
示例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()
}
开发者ID:Bii03,项目名称:weather-monitor,代码行数:42,代码来源:RestService.scala
示例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)
}
开发者ID:poguez,项目名称:class_orchestration_api,代码行数:36,代码来源:Main.scala
示例16: RandomAuthService
//设置package包名称以及导入依赖的类
package com.rndmi.messaging.auth
import java.util.logging.Logger
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import io.bigfast.messaging.MessagingServer._
import io.bigfast.messaging.auth.AuthService
import io.grpc.Metadata
import spray.json.{JsonParser, ParserInput}
class RandomAuthService extends AuthService {
import RandomAuthService._
override def doAuth(metadata: Metadata) = {
val authorization = metadata.get[String](authorizationKey)
val session = metadata.get[String](sessionKey)
logger.info(s"Checking auth for $authorization, $session")
val httpResponse = http.singleRequest(
HttpRequest(uri = uri).withHeaders(
AuthorizationHeader(authorization),
SessionHeader(session)
)
)(materializer)
httpResponse flatMap { response =>
val responseEntity = response.entity
val eventualRandomResponse = unmarshaller.apply(responseEntity)
logger.info(s"Parsed this response: $eventualRandomResponse")
eventualRandomResponse
} map { resp =>
resp.data.userId.toString
}
}
}
object RandomAuthService extends JsonSupport {
val authorizationKey = Metadata.Key.of("AUTHORIZATION", Metadata.ASCII_STRING_MARSHALLER)
val sessionKey = Metadata.Key.of("X-AUTHENTICATION", Metadata.ASCII_STRING_MARSHALLER)
val http = Http()
val uri = ConfigFactory.load().getString("auth.uri")
implicit val materializer = ActorMaterializer()
val logger = Logger.getLogger(this.getClass.getName)
val unmarshaller: Unmarshaller[HttpEntity, RandomResponse] = {
Unmarshaller.byteArrayUnmarshaller mapWithCharset { (data, charset) =>
JsonParser(ParserInput(data)).asJsObject.convertTo[RandomResponse]
}
}
}
开发者ID:kykl,项目名称:mva,代码行数:61,代码来源:RandomAuthService.scala
示例17: HttpFetcher
//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.external
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.client.RequestBuilding
import akka.http.scaladsl.model._
import akka.stream.Materializer
import akka.stream.scaladsl._
import au.csiro.data61.magda.util.Http.getPort
import scala.concurrent.{ ExecutionContext, Future }
class HttpFetcher(interfaceConfig: InterfaceConfig, implicit val system: ActorSystem,
implicit val materializer: Materializer, implicit val ec: ExecutionContext) {
lazy val connectionFlow: Flow[HttpRequest, HttpResponse, Any] =
Http().outgoingConnection(interfaceConfig.baseUrl.getHost, getPort(interfaceConfig.baseUrl))
def request(path: String): Future[HttpResponse] =
interfaceConfig.fakeConfig match {
case Some(fakeConfig) => Future {
val file = io.Source.fromInputStream(getClass.getResourceAsStream(fakeConfig.datasetPath))
val response = new HttpResponse(
status = StatusCodes.OK,
headers = scala.collection.immutable.Seq(),
protocol = HttpProtocols.`HTTP/1.1`,
entity = HttpEntity(ContentTypes.`application/json`, file.mkString))
file.close()
response
}
case None => {
val request = RequestBuilding.Get(s"${interfaceConfig.baseUrl.getPath}${path}")
Source.single(request).via(connectionFlow).runWith(Sink.head)
}
}
}
开发者ID:TerriaJS,项目名称:magda-ckan,代码行数:40,代码来源:HttpFetcher.scala
示例18: RestServer
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.project
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import org.apache.spark.sql.SparkSession
class RestServer(implicit val system:ActorSystem,
implicit val materializer:ActorMaterializer,implicit val
sparkSession:SparkSession) extends RestService{
def startServer(address:String, port:Int) = {
Http().bindAndHandle(route,address,port)
}
}
object RestServer {
def main(args: Array[String]) {
implicit val actorSystem = ActorSystem("rest-server")
implicit val materializer = ActorMaterializer()
implicit val sparkSession:SparkSession = SparkSession.builder().master("local").
appName("Rest Server context").getOrCreate()
val server = new RestServer()
server.startServer("localhost",8080)
println("running server at localhost 8080")
}
}
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:32,代码来源:RestServer.scala
示例19: Server
//设置package包名称以及导入依赖的类
package org.snowflake.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.{Source, StdIn}
object Server {
def main(args: Array[String]) {
implicit val system = ActorSystem("system")
implicit val materializer = ActorMaterializer()
// needed for the future flatMap/onComplete in the end
implicit val executionContext = system.dispatcher
val raw = Source.fromInputStream(getClass.getResourceAsStream("/response.json")).mkString
val route =
path("api" / "v1" / "test") {
get {
complete(HttpEntity(ContentTypes.`application/json`, raw))
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8008)
println(s"Server online at http://localhost:8008/\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
}
}
开发者ID:shakhovv,项目名称:snowflake,代码行数:37,代码来源:Server.scala
示例20: Main
//设置package包名称以及导入依赖的类
package de.innfactory.bootstrap
import akka.actor.ActorSystem
import akka.event.{Logging, LoggingAdapter}
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import de.innfactory.bootstrap.http.HttpService
import de.innfactory.bootstrap.services.{AuthService, DummyService}
import de.innfactory.bootstrap.utils.{AWSCognitoValidation, Configuration, FlywayService}
import scala.concurrent.ExecutionContext
object Main extends App with Configuration {
// $COVERAGE-OFF$Main Application Wrapper
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 authService = new AuthService(new AWSCognitoValidation(authCognito, log))
val dummyService = new DummyService()
val httpService = new HttpService(authService, dummyService)
Http().bindAndHandle(httpService.routes, httpHost, httpPort)
// $COVERAGE-ON$
}
开发者ID:innFactory,项目名称:bootstrap-akka-http,代码行数:31,代码来源:Main.scala
注:本文中的akka.http.scaladsl.Http类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论