本文整理汇总了Scala中akka.http.scaladsl.server.RequestContext类的典型用法代码示例。如果您正苦于以下问题:Scala RequestContext类的具体用法?Scala RequestContext怎么用?Scala RequestContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RequestContext类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Demo1
//设置package包名称以及导入依赖的类
package lew.bing.akka.http
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.{Directive, RequestContext, Route, RouteResult}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Flow
import scala.io.StdIn
object Demo1 {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem("my-http")
implicit val materializer = ActorMaterializer()
// needed for the future flatMap/onComplete in the end
implicit val executionContext = system.dispatcher
val route:Route =
path("hello"){
get {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,"<h1>Say hello to akka-http</h1>"))
}
}
val map = Flow[RequestContext].map(route)
//???????????
val bindingFuture = Http().bindAndHandle(route,"localhost",9898)
println(s"Server online at http://localhost:9898/\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
}
}
示例2: DRoute
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl
import akka.http.documenteddsl.documentation.Documentation
import akka.http.scaladsl.server.{RequestContext, _}
import scala.concurrent.Future
class DRoute(
underlying: Route,
writer: Documentation => Documentation = identity) extends Route {
def selfDescribe(doc: Documentation): Documentation = writer apply doc
override def apply(ctx: RequestContext): Future[RouteResult] = underlying apply ctx
override def toString = "DocumentedRoute()"
}
object DRoute {
def apply(r: Route) = new DRoute(r)
def maybe(r: Route): DRoute = {
r match {
case r: DRoute => r
case _ => new DRoute(r)
}
}
def copyDocumentation(from: DRoute, to: Route): DRoute = new DRoute(to, from.selfDescribe)
}
示例3: ImperativeRequestContext
//设置package包名称以及导入依赖的类
package org.cristal.api.helper
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{RequestContext, Route, RouteResult, StandardRoute}
import scala.concurrent.Promise
final class ImperativeRequestContext(ctx: RequestContext, promise: Promise[RouteResult]) {
private implicit val ec = ctx.executionContext
def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete)
def fail(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete)
}
trait ApiHelper {
def notImplementedResponse(msg: String = ""): StandardRoute =
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
s"<h1>We plan to support this resource soon.</h1>"))
def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext =>
val p = Promise[RouteResult]()
inner(new ImperativeRequestContext(ctx, p))
p.future
}
}
示例4: RequestProcessingActor
//设置package包名称以及导入依赖的类
package wyt.backend.server
import akka.actor.ActorLogging
import akka.actor.Actor
import akka.actor.Actor._
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Props
import java.util.Date
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.server.RequestContext
class RequestProcessingActor[T](nextActor: Props) extends Actor with ActorLogging {
implicit val system = ActorSystem()
var returnTo:ActorRef = null
def receive = {
case ctx: RequestContext => {
returnTo = sender
log info "starting Request Processing... returnTo set to " + returnTo
val a = context.actorOf(nextActor, nextActor.actorClass().getSimpleName)
a ! RequestEvent(ctx)
}
case res: ResponseEvent => {
log info "finishing Request Processing..."
log info "returning msg hiXXX to " + returnTo
returnTo ! "hiXXX"
}
case any:Any => {
log error "??? received msg of type " + any.getClass().getName + " with value " + any.toString()
}
}
}
示例5: RequestProcessingActor
//设置package包名称以及导入依赖的类
package io.skysail.core.akka
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor.actorRef2Scala
import akka.http.scaladsl.server.RequestContext
class RequestProcessingActor[T](nextActor: Props) extends Actor with ActorLogging {
var returnTo: ActorRef = null
def receive = {
case (ctx: RequestContext, actor: ActorRef) => receiveRequestContext(ctx, actor)
case res: ResponseEvent[T] => receiveResponseEvent(res)
case any: Any => log error "??? received msg of type " + any.getClass().getName + " with value " + any.toString()
}
private def receiveRequestContext(ctx: RequestContext, resourceActor: ActorRef) = {
returnTo = sender
val a = context.actorOf(nextActor, nextActor.actorClass().getSimpleName)
a ! RequestEvent(ctx,resourceActor)
}
private def receiveResponseEvent(res: ResponseEvent[T]) = {
println ("RESPONSE")
println (res.resource)
returnTo ! res
}
}
示例6: ApplicationActor
//设置package包名称以及导入依赖的类
package io.skysail.core.server
import akka.actor.{Actor, ActorLogging, ActorRef, PoisonPill, Props}
import java.util.concurrent.atomic.AtomicInteger
import akka.http.scaladsl.server.RequestContext
import io.skysail.core.akka.ResponseEvent
import io.skysail.core.model.ApplicationModel
object ApplicationActor {
case class GetAppModel()
}
class ApplicationActor(appModel: ApplicationModel) extends Actor with ActorLogging {
val cnt = new AtomicInteger(0)
var nextActor: ActorRef = null
val originalSender = sender
var sendBackTo: ActorRef = null
def receive = in
import context._
def in: Receive = {
case (ctx:RequestContext,cls : Class[_]) => {
log debug s"in AppActor... got message ($ctx, $cls)"
sendBackTo = sender
nextActor = context.actorOf(Props.apply(cls)) // ResourceActor, e.g. AppsResource
nextActor ! ctx
become(out)
}
case _: ApplicationActor.GetAppModel => sender ! appModel
case msg: Any => log info s"IN: received unknown message '$msg' in ${this.getClass.getName}"
}
def out: Receive = {
case _: ApplicationActor.GetAppModel => sender ! appModel
case e: ResponseEvent[_] => {
log debug "out AppActor... " + e
log debug "sending to " + sendBackTo
sendBackTo ! e
//log info "stopping actor: " + chainRoot
//context.stop(chainRoot)
become(in)
nextActor ! PoisonPill
}
case msg: Any => log info s"OUT: received unknown message '$msg' in ${this.getClass.getName}"
}
}
示例7: doRequest
//设置package包名称以及导入依赖的类
package com.github.aproxy.http
import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.server.RequestContext
import akka.http.scaladsl.{Http, HttpExt}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Sink, Source}
import com.github.aproxy.internal.AppConfig
import scala.concurrent.{ExecutionContext, Future}
trait ProxyServer {
implicit val actorSystem: ActorSystem
def doRequest(path: RequestContext, backOff: Int = 2)
(implicit ec: ExecutionContext): Future[HttpResponse]
protected def http: HttpExt
protected def routerFlowMapper: Map[String, Flow[_, _, Future[_]]]
}
// TODO: Add backoff
class DefaultProxyServer(implicit val actorSystem: ActorSystem,
implicit val mat: ActorMaterializer) extends ProxyServer {
override protected val http: HttpExt = Http(actorSystem)
override protected val routerFlowMapper = AppConfig.routes.mapValues(route => http.outgoingConnection(route.base, route.port))
override def doRequest(ctx: RequestContext, backoff: Int = 2)(implicit ec: ExecutionContext): Future[HttpResponse] = {
routerFlowMapper.get(ctx.request.uri.path.toString) match {
case Some(flow) => Source.single(ctx.request).via(flow).runWith(Sink.head)
case _ => throw new Exception()
}
}
}
示例8: AutowireServer
//设置package包名称以及导入依赖的类
package server
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{RequestContext, RouteResult}
import akka.util.ByteString
import boopickle.Default._
import java.nio.ByteBuffer
import scala.concurrent.{Future, ExecutionContext}
import model.Api
object AutowireServer extends autowire.Server[ByteBuffer, Pickler, Pickler] {
override def read[R: Pickler](p: ByteBuffer) = Unpickle[R].fromBytes(p)
override def write[R: Pickler](r: R) = Pickle.intoBytes(r)
def dispatch(url: List[String])(implicit ec: ExecutionContext): RequestContext => Future[RouteResult] =
entity(as[ByteString]) { entity =>
val service = InMemService
val body = Unpickle[Map[String, ByteBuffer]].fromBytes(entity.asByteBuffer)
val request: Future[ByteBuffer] = AutowireServer.route[Api](service)(autowire.Core.Request(url, body))
onSuccess(request)(buffer => complete(ByteString(buffer)))
}
}
示例9: SkillSlice
//设置package包名称以及导入依赖的类
package com.microworkflow.rest
import akka.actor.{ActorRefFactory, ActorSystem}
import akka.http.scaladsl.{Http, HttpExt}
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{RequestContext, Route}
import akka.stream.Materializer
import com.microworkflow.rest.SkillHandler.ProcessRequest
import de.heikoseeberger.akkahttpcirce.CirceSupport._
import io.circe.Json
import io.circe.generic.auto._
import io.github.todokr.Emojipolation._
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
class SkillSlice()(implicit actorSystem: ActorSystem, m: Materializer) {
val http = Http()
val routes: Route = {
path("") {
pathEnd {
get {
complete(HttpResponse(entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, emoji":+1:")))
} ~ post {
entity(as[Json]) { json ?
val q = json
processRequest(json)
}
}
}
}
}
def processRequest(json: Json): Route = {
requestCotext: RequestContext ? {
implicit val askTimeout: Timeout = 3456.millis
val requestHandler = actorSystem.actorOf(SkillHandler.props(m, http))
requestCotext.complete(requestHandler.ask(ProcessRequest(json)).mapTo[Json])
}
}
}