获得响应时间

时间:2015-06-10 10:07:06

标签: scala http scala-dispatch

是否有一种简单的方法可以获取请求到网址的响应时间(除了单独跟踪代码中的时间)?

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")
    }
  }

2 个答案:

答案 0 :(得分:1)

这是计算经过时间的另一种方法,可能需要更多的自定义(如处理失败,最有可能public static boolean hasTerminatedExecution(Process p) { try { p.exitValue(); return true; } catch (IllegalThreadStateException exception) { return false; // exception thrown if process didn't terminated yet } } ),但我认为这有点习惯。它仅适用于NonFatal s。

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

Future

然后创建一个包装未来以执行的方法,并在失败时处理该情况(如果您不喜欢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) ' Promise,可能会使用Future map方法(因为它们需要隐式recoverWith))。

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))
         }
  }
}

答案 1 :(得分:0)

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

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