Akka(31): Http:High-Level-Api,Route rejection handling

   Route 是Akka-http routing DSL的核心部分,使用户能比较方便的从http-server的角度筛选http-request、进行server运算、构建回复的http-response。所谓筛选http-request主要目的是容许request进入下一内层Route,或者拒绝reject request。比如这个~符号:它连接了上下两个独立的Route。如果上面的Route拒绝了一个request,那么下面的Route就会接着尝试这个request。一般来说:当一个筛选功能的Directive如get遇到一个不符合筛选条件的request时,它会拒绝reject这个request进入下一层Route。这时用~符号链接的下一组Route会接着尝试,直到链条最后一组Route。整个过程中的这些rejection事件会被记录下来最后由某个隐式或明式的RejectionHandler实例把这组rejection转化成HttpResponse返回用户。rejection也可以直接调用requestContext.reject(...)产生。Akka-http是通过在运行Route时用Route.seal(route)的方式来确保所有rejection在最终都会得到处理:

  override def seal(system: ActorSystem, materializer: Materializer): Route = {
    implicit val s = system
    implicit val m = materializer

    RouteAdapter(scaladsl.server.Route.seal(delegate))
  }

下面是Route.seal()函数定义:

  /**
   * "Seals" a route by wrapping it with default exception handling and rejection conversion.
   *
   * A sealed route has these properties:
   *  - The result of the route will always be a complete response, i.e. the result of the future is a
   *    ``Success(RouteResult.Complete(response))``, never a failed future and never a rejected route. These
   *    will be already be handled using the implicitly given [[RejectionHandler]] and [[ExceptionHandler]] (or
   *    the default handlers if none are given or can be found implicitly).
   *  - Consequently, no route alternatives will be tried that were combined with this route
   *    using the ``~`` on routes or the [[Directive.|]] operator on directives.
   */
  def seal(route: Route)(implicit
    routingSettings: RoutingSettings,
                         parserSettings:   ParserSettings   = null,
                         rejectionHandler: RejectionHandler = RejectionHandler.default,
                         exceptionHandler: ExceptionHandler = null): Route = {
    import directives.ExecutionDirectives._
    // optimized as this is the root handler for all akka-http applications
    (handleExceptions(ExceptionHandler.seal(exceptionHandler)) & handleRejections(rejectionHandler.seal))
      .tapply(_ ⇒ route) // execute above directives eagerly, avoiding useless laziness of Directive.addByNameNullaryApply
  }

RejectionHandler.default是Akka-http提供的默认handler。我们也可以把自定义的隐式RejectionHandler实例放在可视域内就会自动被调用了。下面是一个自定义RejectionHandler例子:

      RejectionHandler.newBuilder()
        .handle { case MissingCookieRejection(cookieName) =>
          complete(HttpResponse(BadRequest, entity = "No cookies, no service!!!"))
        }
        .handle { case AuthorizationFailedRejection =>
          complete((Forbidden, "You're out of your depth!"))
        }
        .handle { case ValidationRejection(msg, _) =>
          complete((InternalServerError, "That wasn't valid! " + msg))
        }
        .handleAll[MethodRejection] { methodRejections =>
          val names = methodRejections.map(_.supported.name)
          complete((MethodNotAllowed, s"Can't do that! Supported: ${names mkString " or "}!"))
        }
        .handleNotFound { complete((NotFound, "Not here!")) }
        .result()

所有Rejection类型都在Rejection.scala里定义。result()函数返回Rejection类型:

   def result(): RejectionHandler =
      new BuiltRejectionHandler(cases.result(), notFound, isDefault)

我们也可以用mapRejetionResponse对现成handler中产生的HttpResponse进行转换: 

      RejectionHandler.default
        .mapRejectionResponse {
          case res @ HttpResponse(_, _, ent: HttpEntity.Strict, _) =>
            // since all Akka default rejection responses are Strict this will handle all rejections
            val message = ent.data.utf8String.replaceAll("\"", """\"""")
            
            // we copy the response in order to keep all headers and status code, wrapping the message as hand rolled JSON
            // you could the entity using your favourite marshalling library (e.g. spray json or anything else) 
            res.copy(entity = HttpEntity(ContentTypes.`application/json`, s"""{"rejection": "$message"}"""))
            
          case x => x // pass through all other types of responses
        }

下面是一个比较全面的RejectionHandle应用示范:

akka.actor._
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.Directives._
import akka.stream._
import akka.stream.scaladsl._
import akka._
import StatusCodes._
import scala.concurrent._

object RejectionHandlers {
  implicit val rejectionHandler =
    (RejectionHandler.newBuilder()
      .handle { case MissingCookieRejection(cookieName) =>
        complete(HttpResponse(BadRequest, entity = "No cookies, no service!!!"))
      }
      .handle { case AuthorizationFailedRejection =>
        complete((Forbidden, "You're out of your depth!"))
      }
      .handle { case ValidationRejection(msg, _) =>
        complete((InternalServerError, "That wasn't valid! " + msg))
      }
      .handleAll[MethodRejection] { methodRejections =>
      val names = methodRejections.map(_.supported.name)
      complete((MethodNotAllowed, s"Can't do that! Supported: ${names mkString " or "}!"))
      }
      .handleNotFound {
        extractUnmatchedPath { p =>
          complete((NotFound, s"The path you requested [${p}] does not exist."))
        }
      }
      .result())
      .mapRejectionResponse {
        case res @ HttpResponse(_, _, ent: HttpEntity.Strict, _) =>
          // since all Akka default rejection responses are Strict this will handle all rejections
          val message = ent.data.utf8String.replaceAll("\"", """\"""")

          // we copy the response in order to keep all headers and status code, wrapping the message as hand rolled JSON
          // you could the entity using your favourite marshalling library (e.g. spray json or anything else)
          res.copy(entity = HttpEntity(ContentTypes.`application/json`, s"""{"rejection mapped response": "$message"}"""))

        case x => x // pass through all other types of responses
      }
}

object RejectionHandlerDemo extends App {
  import RejectionHandlers._

  implicit val httpSys = ActorSystem("httpSys")
  implicit val httpMat = ActorMaterializer()
  implicit val httpEc = httpSys.dispatcher

  val (port, host) = (8011,"localhost")

  val route: Flow[HttpRequest, HttpResponse, NotUsed] = pathPrefix("hello" ~ PathEnd) {
    get {
      complete {Future("OK")}
      //HttpEntity(ContentTypes.`text/html(UTF-8)`,"<h1> hello http server </h1>")}
    }
  }

  val bindingFuture: Future[Http.ServerBinding] = Http().bindAndHandle(route,host,port)

  println(s"Server running at $host $port. Press any key to exit ...")

  scala.io.StdIn.readLine()

  bindingFuture.flatMap(_.unbind())
    .onComplete(_ => httpSys.terminate())

}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏IT笔记

JAVA工作三年面试(三)

经过前面两次的面试,这里就马上转到第三家公司了的面试了,这里简称 B,工作地点和上一篇所讲述的 W 公司在一个城市,是面完 W 之后第二天去的,说出名字的话大多...

2596
来自专栏Java Edge

观察者模式

3057
来自专栏决胜机器学习

PHP数据结构(四) ——队列

PHP数据结构(四)——队列以及简单消息存取 (原创内容,转载请注明来源,谢谢) 队列也是一种特殊的线性表,和栈很相似,区别在于队列对于数据增加和删除的限制和...

3716
来自专栏狂码一生

用MFC写一个聊天室程序 - 学习笔记

下面的服务器端与客户端的程序与步骤是我在学习MFC网络编程写一个聊天室程序所写的程序,在这里作一个笔记,也希望能帮到一部分刚刚学习的朋友,一起共勉,一起努力历进...

51514
来自专栏灯塔大数据

每周学点大数据 | No.41 join 操作

No.41期 join 操作 Mr. 王:第一个话题就是 join 操作。 join 操作在数据库中还是非常常见的。 小可:这个 join 指的是笛卡儿积操...

3637
来自专栏程序员互动联盟

Java高级工程师需要掌握哪些核心点?

每逢长假都会有很多程序员跳槽,十一、过年是跳槽黄金时刻,尤其是过年。过年的时候年终奖到手,没有了多少牵挂,年终同学同事聚会比较多,沟通的就多,各种工作机会的消息...

36110
来自专栏Java Edge

策略模式一 简介二 策略模式的结构三 lambda实例

26612
来自专栏orientlu

BLE 广播格式定义

低功耗蓝牙两类报文 : 广播报文 和 数据报文。 本文讨论广播报文数据段,不包括完整报文其他部分,比如前导,接入地址等

552
来自专栏SDNLAB

OpenFlow 1.3 学习笔记

因为7、8月我跟小伙伴们在备战今年的全国大学生SDN大赛,9月在全身心投入准备特殊人才保研的专家答辩,所以好久没有新文章跟大家见面啦。现在一切尘埃落定,继续卯足...

3417
来自专栏乐沙弥的世界

MySQL HA架构下innodb_flush_log_at_trx_commit及sync_binlog参数

      HeartBeat + DRBD以及MySQL replication是很多企业比较普遍使用的方式。对于数据的完整性和一致性的问题,这两种架构需要考...

712

扫码关注云+社区