[Groovy] 在Groovy中优雅的实现do while

Groovy原生是不支持do while的,参考html

曲线救国,能够这么用闭包

class Looper {
   private Closure code

   static Looper loop( Closure code ) {
      new Looper(code:code)
   }

   void until( Closure test ) {
      code()
      while (!test()) {
         code()
      }
   }
}
import static Looper.*

int i = 0
loop {
   println("Looping : "  + i)
   i += 1
} until { i == 5 }

注意 until 这里用的是大括号,才能让条件变成一个闭包oop

实际使用场景,咱们接口中须要调用外部接口,外部接口不是很稳定,容易出错,因此加入了出错重试机制,一共重试三次,三次事后仍是不行才放弃。

post

def responseString = null
        Exception exception = null
        //出错重试
        int retry = 0

        Looper.loop {
            try{
                responseString = HttpUtil.post(url, JSONObject.toJSONString(post), header, 10000, 10000)
            }catch (Exception ex){
                exception = ex
            }finally{
                retry++
            }
        }until { exception == null || retry == 3 }


        if(exception != null){
            throw exception
        }
相关文章
相关标签/搜索