URLFetchがIOExceptionを投げるか、ステータス500が返ってきた場合にリトライ。
import com.google.appengine.api.urlfetch._
val UFS = URLFetchServiceFactory.getURLFetchService()
def retryingURLFetch[A](r: HTTPRequest, retry: Int)(f: HTTPResponse => A): A = {
try {
val res = UFS.fetch(r)
res.getResponseCode match {
case 500 =>
if (retry <= 0) f(res)
else retryingURLFetch(r, retry - 1)(f)
case _ => f(res)
}
} catch {
case e: java.io.IOException =>
if (retry <= 0) throw e
retryingURLFetch(r, retry - 1)(f)
}
}
使用例
import java.net.URL
import com.google.appengine.api.urlfetch._
retryingURLFetch(new HTTPRequest(new URL("http://pomu0325.blogspot.com")), 2) {
res => println(new String(res.getContent, "utf-8"))
}
不安定なAPIを呼ぶ時とかに使えそう。
0 件のコメント:
コメントを投稿