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

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

曲线救国,可以这么用

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 这里用的是大括号,才能让条件变成一个闭包

实际使用场景,我们接口中需要调用外部接口,外部接口不是很稳定,容易出错,所以加入了出错重试机制,一共重试三次,三次过后还是不行才放弃。

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
        }
欢迎关注Java流水账公众号
原文地址:https://www.cnblogs.com/guofu-angela/p/10689035.html