---
title: "scala - turorial RetryTemplate"
author: "暗夜骑士0376"
date: "2013-03-23T23:17:17Z"
tags: []
categories: ["编程语言"]
slug: "scala-turorial-retrytemplate"
draft: false
lastmod: "2013-03-23T23:16:24Z"
id: 1835567
url: "https://moliniao.iteye.com/blog/1835567"
---

在公司里面用java实现了一个RetryTemplate的模板，可能spring里面已经实现了，但是用scala实现了一个很简单的，就当作学习吧。
下面是RetryTemplate.scala

```java


class RetryTemplate(c: Int, d: Long) {

	require(c > 0 && d > 0)
	val count = c
	val delay = d

	def this() {
		this(10, 500)
	}

	def retryOperation(action: () => Unit): Unit = {
		def wrapAction(): Boolean = {
			action()
			true
		}
		this.retryOperation(classOf[boolean], wrapAction)
	}

	def retryOperation[t <: any](returnType: Class[t], action: () => T): T = {
//scala里面的变量初始化真是坑跌。
		var exception: Throwable = null.asInstanceOf[throwable]
		var result: T = null.asInstanceOf[t]
//scala里面没有break判断，直接return又会报ReturnNotControl的exception.
		(1 to count).toStream.takeWhile(i => !exception.isInstanceOf[finishstatus]).foreach {
			_ =>
				try {
					result = action()
					exception = new FinishStatus
				} catch {
					case ex: Throwable => {
						exception = ex
						delayTime
					}
				}
		}

		if (exception.isInstanceOf[finishstatus]) {
			result
		} else {
			Console.println("retry attempt max times, finish retry.")
			throw exception
		}
	}

	def delayTime(): Unit = {
		Thread.sleep(delay);
	}
}

private class FinishStatus extends Throwable with NoStackTrace


```


下面是测试代码

```java

class HelloworldModule extends RetryTemplate {

	def sayHello() = {
        Console.println("sayHello")
//throw new IllegalStateException
    }
	
}

object TestReretyTemplate {

	def main(args: Array[string]) {
	    val helloworldModule = new HelloworldModule
	    helloworldModule.retryOperation(helloworldModule.sayHello)
	}

}

```

希望对scala有更深理解的童鞋能够更好的实现。