Fork me on GitHub

实现一个简单的方法重试工厂

源码如下:

 1 package com.sankuai.sos.server.test;
 2 
 3 import org.junit.Test;
 4 import org.slf4j.Logger;
 5 import org.slf4j.LoggerFactory;
 6 
 7 /**
 8  * Created by zhengbin on 2018/7/20
 9  */
10 public class TryFactory {
11     private static final Logger LOGGER = LoggerFactory.getLogger(TryFactory.class.getName());
12 
13     /**
14      * 重试
15      * @param interval  重试间隔
16      * @param times     重试次数
17      * @param method    重试执行方法
18      * @param <R>       重试执行方法返回类型
19      */
20     private static <R> R tryTo(Long interval,
21                               Integer times,
22                               TryMethod<R> method) {
23         R result = null;
24         Integer tryTimes = 0;
25         try {
26             while (times > tryTimes && result == null) {
27                 tryTimes++;
28                 result = method.getResult();
29                 if (result == null && tryTimes < times) {
30                     Thread.sleep(interval);
31                 }
32             }
33             return result;
34         } catch (Throwable e) {
35             LOGGER.error("", e);
36         }
37         return null;
38     }
39 
40     private interface TryMethod<R> {
41         R getResult();
42     }
43 
44     @Test
45     public void test1() {
46         String s = "zhengbin";
47         for (int i = 1;i < 4;i++) {
48             final int fI = i;
49             String res = TryFactory.tryTo(300L, 3, () -> getStr(s, fI));
50             System.out.println("try suc,res:"+res);
51         }
52     }
53 
54     private String getStr(String str, Integer v) {
55         if (v != 3) {
56             System.out.println("try param:" + v);
57             return null;
58         }
59         System.out.println("try:suc");
60         return "result:" + str;
61     }
62 }

 输出:

 

posted @ 2018-07-20 11:34  郑斌blog  阅读(504)  评论(0编辑  收藏  举报