[scala] retry

scala 2016. 10. 6. 19:20

spring4에서는 Retryable을 사용하면 retry 관련 코드가 짧아진다.


 @Retryable(maxAttempts = 2, backoff = @Backoff(delay = 0))
String call(String url);




scala에서는 아예 쉽게 retry를 쉽게 만들 수 있다. 


아래 링크를 참조하면 좋은 결과를 얻을 수 있다. 꼬리 재귀와 커링을 사용했다. 


http://stackoverflow.com/questions/7930814/whats-the-scala-way-to-implement-a-retry-able-call-like-this-one



object Main extends App {
@annotation.tailrec
def retry[T](n: Int)(fn: => T): T = {
util.Try { fn } match {
case util.Success(x) => x
case _ if n > 1 => retry(n - 1)(fn)
case util.Failure(e) => throw e
}
}

var i = 0;
retry(3) {
i += 1
test(i)
}

def test(i: Int): Unit = {
if (i == 1 || i == 2) throw new Exception("XXX")
if (i == 3) {
System.out.println(i)
}
}
}


결과는 3이다. 








Posted by '김용환'
,