0
몇 가지 동시 HTTP GET 요청을 보내고 모든 응답이 만료 될 때까지 대기하는 함수를 작성한다고 가정합니다. 하나 이상의 응답이 상태가 200
이 아니거나 제한 시간 내에 있지 않으면 내 함수가 실패를 반환해야합니다.동시 HTTP GET 요청을 보낼 선물
나는 이런 식으로이 기능 tryGets
을 쓰고 있어요 :
import java.net.URL
import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.util.Try
def unsafeGet(url: URL): String = {
val in = url.openStream()
scala.io.Source.fromInputStream(in).mkString
}
def futureGet(url: URL)
(implicit ec: ExecutionContext): Future[String] = Future {
unsafeGet(url)
}
def tryGets(urls: Seq[URL], timeOut: Duration)
(implicit ec: ExecutionContext): Try[Seq[String]] = Try {
val fut = Future.sequence(urls.map(futureGet))
Await.result(fut, timeOut)
}
는 의미가 있습니까? 시간이 초과 된 경우 향후 인스턴스가 누출되지 않습니까?
당신은 독해력을 조사 했습니까? 다음은 그것을 사용하는 방법에 대한 좋은 기사입니다 : http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html –
for-comprehension은 선물이 아닌 동시에 순차적으로 선물을 실행합니다. – Michael
미리 신고하지 않는 경우. 그래서 val x = Future {};를 할 수 있습니다. for {result <- x} 대신에 {result <- Future {}} –