在Play中删除阻止调用

时间:2016-12-28 04:01:04

标签: scala playframework

我正在尝试将每个请求花费的时间用于将其发送到Play应用程序中的远程系统。

适用于异步操作的案例类TimeAction不适用于同步操作

//Helper
case class TimeAction(label: String] = Map()) = {
  def logging[A](action: Action[A])(implicit ec: ExecutionContext) = 
    Action.async(action.parser) { request =>
      MetricLogger.timeFuture(s"controllers.action.$label") {
        action(request)
    }
  }
}

//controller
def test =
  TimeAction("toto.test.sync").logging {
    Action { _ =>
      Thread.sleep(4000)
      Ok
    }
  }
// expected output 4003 milliseconds but got 3 milliseconds

def testAsync =
  TimeAction("toto.test.async").logging {
    Action.async { _ =>
      Future {
        Thread.sleep(4000)
        Ok
      }
    }
  }
// go 4003 milliseconds as expected

//calculate time elapsed during a future
def timeImpl[T](f: Future[T], 
                onError: (Duration, Throwable) => Unit, 
                onSuccess: (Duration, T) => Unit)(implicit ec: ExecutionContext): Future[T] = {
    val start = System.nanoTime
    f.onComplete {
      case Success(d) => onSuccess(calculateTimeDiff(start, System.nanoTime()), d)
      case Failure(e) => onError(calculateTimeDiff(start, System.nanoTime()), e)
    }
    f
}

我认为该动作在到达我的TimeAction之前就已执行,并且仅在瞬间Future中被包裹。你知道哪里吗 ?我错过了什么?

我正在使用Play 2.3

0 个答案:

没有答案