添加Maven依赖:
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>1.1.0.RELEASE</version> </dependency>
代码结构:
源码:
1 package Exception; 2 3 /** 4 * Created by zhengbin06 on 2017/2/14. 5 */ 6 public class Clazz { 7 private int i = 0; 8 public Student getStudent() throws SException { 9 if(++i != 3) { 10 System.out.println(i); 11 throw new SException(); 12 } 13 return new Student(); 14 } 15 }
1 package Exception; 2 3 import org.springframework.retry.RetryCallback; 4 import org.springframework.retry.RetryContext; 5 import org.springframework.retry.policy.SimpleRetryPolicy; 6 import org.springframework.retry.support.RetryTemplate; 7 import java.util.HashMap; 8 import java.util.Map; 9 10 public class RetryUtil { 11 12 public static <T> T requestThridtWithRetry(final SRequest<T> sRequest) throws Exception { 13 // 重试模板 14 RetryTemplate template = new RetryTemplate(); 15 16 // 何种异常将触发重试 17 Map<Class<? extends Throwable>, Boolean> map = new HashMap<Class<? extends Throwable>, Boolean>(); 18 map.put(SException.class, true); 19 20 // 重试次数 21 int retryTimes = 3; 22 23 // 定义重试规则 24 SimpleRetryPolicy policy = new SimpleRetryPolicy(retryTimes, map); 25 template.setRetryPolicy(policy); 26 27 // 执行重试 28 return template.execute(new RetryCallback<T, Exception>() { 29 public T doWithRetry(RetryContext context) throws SException { 30 return sRequest.request(); 31 } 32 }); 33 34 } 35 }
1 package Exception; 2 3 /** 4 * Created by zhengbin06 on 2017/2/14. 5 */ 6 public class SException extends Exception { 7 public SException() { 8 super("getStudenException"); 9 } 10 }
1 package Exception; 2 3 /** 4 * Created by zhengbin06 on 2017/2/14. 5 */ 6 public interface SRequest<T> { 7 public T request() throws SException; 8 }
1 package Exception; 2 3 /** 4 * Created by zhengbin06 on 2017/2/14. 5 */ 6 public class Student { 7 @Override 8 public String toString() { 9 return "I'am student"; 10 } 11 }
1 package Exception; 2 3 /** 4 * Created by zhengbin06 on 2017/2/14. 5 */ 6 public class TestRetry { 7 public static void main(String[] args) throws Exception { 8 final Clazz finalS = new Clazz(); 9 Student student = null; 10 try { 11 student = RetryUtil.requestThridtWithRetry(new SRequest<Student>() { 12 public Student request() throws SException { 13 return finalS.getStudent(); 14 } 15 }); 16 } catch (Exception e) { 17 e.printStackTrace(); 18 } 19 System.out.println(student.toString()); 20 } 21 }