无法理解lagom

时间:2017-08-04 06:31:25

标签: lagom

我正在关注本教程 - https://www.lagomframework.com/documentation/1.3.x/scala/ServiceImplementation.html

我创建了一个已记录的服务

//logged takes a ServerServiceCall as argument (serviceCall) and returns a ServerServiceCall.
  //ServerServiceCall's compose method creates (composes) another ServerServiceCall
  //we are returing the same ServerServiceCall that we received but are logging it using println
  def logged[Request,Response](serviceCall:ServerServiceCall[Request,Response]) = {
    println("inside logged");

    //return new ServerServiceCall after logging request method and uri
    ServerServiceCall.compose({
    requestHeader=>println(s"Received ${requestHeader.method} ${requestHeader.uri}")
    serviceCall
  }
  )}

我使用了如下记录:

  override def hello3 = logged(ServerServiceCall
  { (requestHeader,request) =>
    println("inside ssc")
    val incoming:Option[String] = requestHeader.getHeader("user");

    val responseHeader = ResponseHeader.Ok.withHeader("status","authenticated")
    incoming match {
      case Some(s) => Future.successful((responseHeader,("hello3 found "+s)))
      case None => Future.successful((responseHeader,"hello3 didn't find user"))
    }
  })

我预计会先打印inside ssc然后以已记录的方式进行打印但是相反。不应该首先评估传递给函数的参数吗?

我得到了这个。为什么呢?

inside logged Received POST /hello3 inside ssc

1 个答案:

答案 0 :(得分:2)

logged是您编写的一个函数,它使用ServiceCall并使用自己的ServiceCall进行装饰。稍后,Lagom使用请求标头调用服务调用。您正在修改服务调用点之前的inside logged,在它返回到Lagom之前,因此在调用它之前,这就是它首先被调用的原因。这可以解释一下:

def logged[Request, Response](serviceCall:ServerServiceCall[Request, Response]) = {
  println("3. inside logged method, composing the service call")
  val composed = ServerServiceCall.compose { requestHeader=>
    println("6. now Lagom has invoked the logged service call, returning the actual service call that is wrapped")
    serviceCall
  }

  println("4. Returning the composed service call")
  composed
}

override def hello3 = {
  println("1. create the service call")
  val actualServiceCall: ServerServiceCall[Request, Response] = ServerServiceCall { (requestHeader, request) =>
    println("7. and now the actual service call has been invoked")
    val incoming:Option[String] = requestHeader.getHeader("user");

    val responseHeader = ResponseHeader.Ok.withHeader("status","authenticated")
    incoming match {
      case Some(s) => Future.successful((responseHeader,("hello3 found "+s)))
      case None => Future.successful((responseHeader,"hello3 didn't find user"))
    }
  }

  println("2. wrap it in the logged service call")
  val loggedServiceCall = logged(actualServiceCall)

  println("5. return the composed service call to Lagom")
  loggedServiceCall
}

要记住的重要一点是调用hello3方法调用服务调用,hello3只返回ServiceCall Lagom将用它来调用它。