获取响应时间

Getting response times

是否有一种简单的方法来获取对 url 请求的响应时间(除了在代码中单独跟踪时间)?

import dispatch._, Defaults._
import scala.util.{Failure, Success}

val svc = dispatch.url(url)
  val response: Future[com.ning.http.client.Response] = Http(svc > (x => x))
  response onComplete {
    case Success(content) => {
      println(s"SUCCESS: ${content.getStatusCode()} for $url")
      //how long did this take??
 }
    case Failure(t) => {
      println(s"ERROR: timeout/failure for $url")
    }
  }

您可以用这样的东西包装您的代码(未测试):

class Timer[ResultType](computation: =>Future[ResultType]) {
  private val startTime = System.currentTimeMillis
  val result: Future[ResultType] = computation
  private var endTime: Option[Long] = None
  result.onComplete{case _ => endTime = Some(System.currentTimeMillis)}
  def responseTime: Option[Long] = endTime.map(_ - startTime)
  //probably also provide onComplete and other Future methods wrapping result.
}

object Timer{
  def apply[ResultType](computation: =>Future[ResultType]) = {
    new Timer(computation)
  }
}

您可以使用伴随对象中的工厂方法创建更具体的计时器,以帮助处理您要测量的计算。

用法:

val timedComputation = Timer{Http(svc > (x => x))}
timedComputation.result.onComplete{case _ => ???}
//In a completed event:
val responseTimeInMillis: Long = timedComputation.responseTime.get

这是一种不同的计算经过时间的方法,可能需要更多的定制(比如处理失败,NonFatal 最有可能),但我认为这更符合习惯。不过它只适用于 Futures。

首先为带时间的结果创建一个 class(也可以用元组替换),为带时间的失败创建一个。

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

case class ResultWithTime[ResultType](val result: ResultType, val time: Long)

class FailureWithTime(failure: Throwable, val time: Long) extends Throwable(failure)

然后创建一个方法来包装 future 以执行并处理失败的情况(如果你不喜欢 Futuremap 和 [ 可以使用 Promise =18=] 方法(因为它们需要隐式 ExecutionContext))。

object TimerFuture {
  def apply[ResultType](fut: =>Future[ResultType]): Future[ResultWithTime[ResultType]] = {
    val startTime = System.currentTimeMillis
    fut.map(r => ResultWithTime(r, System.currentTimeMillis - startTime))
       .recoverWith{case t:Throwable =>
         Future.failed(new FailureWithTime(t, System.currentTimeMillis - startTime))
         }
  }
}

这是一个如何使用它的例子:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.io.StdIn


object Y extends App {
   TimerFuture(Future{Thread.sleep(200); "Hello"})
     .onSuccess({case ResultWithTime(r, t) => println(s"Took $t ms to get: $r")})
   TimerFuture(Future{Thread.sleep(100); throw new NullPointerException()})
     .onFailure({case f: FailureWithTime => println(s"Took ${f.time} ms to get: ${f.getCause}")})
   StdIn.readLine()
}