需求: 若代码出现异常,则每隔一段时间重试一下,重试n次
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.Supplier;
public class RetryUtils {
private static final Logger log = LoggerFactory.getLogger(RetryUtils.class);
/**
*
* @param count 重试次数
* @param millisecond 时间间隔
* @param supplier
* @param <T>
* @return
* @throws Exception
*/
public static <T> T retryWhenException(int count, int millisecond, Supplier<T> supplier) throws Exception {
T result = null;
while (count > 0) {
try {
result = supplier.get();
count=0;
} catch (Exception e) {
log.info(e.getMessage());
Thread.sleep(millisecond);
--count;
if (count == 0) {
throw e;
}
}
}
return result;
}
}
使用示例: