2017-12-20 6 views
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) 
} 

는 의미가 있습니까? 시간이 초과 된 경우 향후 인스턴스가 누출되지 않습니까?

+0

당신은 독해력을 조사 했습니까? 다음은 그것을 사용하는 방법에 대한 좋은 기사입니다 : http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html –

+0

for-comprehension은 선물이 아닌 동시에 순차적으로 선물을 실행합니다. – Michael

+0

미리 신고하지 않는 경우. 그래서 val x = Future {};를 할 수 있습니다. for {result <- x} 대신에 {result <- Future {}} –

답변

1

미래의 시간 초과 중 하나 인 경우 미래의 나머지는 열망하고 실행 컨텍스트에서 계속 실행되기 때문에 계속 실행됩니다. 당신이 할 수있는 일은 Urls를 폴드하는 것입니다.

urls.foldleft(Future.sucessful(Seq.empty)) { (future, url) => 
    future.flatMap(accum => futureGet(url).map(accum :+ _)) 
} 
관련 문제