public static Boolean vpmsRetryCoupon(final String userId) { // 構建重試模板實例 RetryTemplate retryTemplate = new RetryTemplate(); // 設置重試策略,主要設置重試次數 SimpleRetryPolicy policy = new SimpleRetryPolicy(10, Collections.<Class<? extends Throwable>, Boolean> singletonMap(Exception.class, true)); // 設置重試回退操作策略,主要設置重試間隔時間 FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy(); fixedBackOffPolicy.setBackOffPeriod(100); retryTemplate.setRetryPolicy(policy); retryTemplate.setBackOffPolicy(fixedBackOffPolicy); // 通過RetryCallback 重試回調實例包裝正常邏輯邏輯,第一次執行和重試執行執行的都是這段邏輯 final RetryCallback<Object, Exception> retryCallback = new RetryCallback<Object, Exception>() { //RetryContext 重試操作上下文約定,統一spring-try包裝 public Object doWithRetry(RetryContext context) throws Exception { boolean result = pushCouponByVpmsaa(userId); if(!result){ throw new RuntimeException();//這個點特別注意,重試的根源通過Exception返回 } return true; } }; // 通過RecoveryCallback 重試流程正常結束或者達到重試上限后的退出恢復操作實例 final RecoveryCallback<Object> recoveryCallback = new RecoveryCallback<Object>() { public Object recover(RetryContext context) throws Exception { // logger.info("正在重試發券::::::::::::"+userId); return null; } }; try { // 由retryTemplate 執行execute方法開始邏輯執行 retryTemplate.execute(retryCallback, recoveryCallback); } catch (Exception e) { // logger.info("發券錯誤異常========"+e.getMessage()); e.printStackTrace(); } return true; } public static void main(String[] args) { vpmsRetryCoupon("43333"); } public static Boolean pushCouponByVpmsaa(String userId){ Random random = new Random(); int a= random.nextInt(10); System.out.println("a是"+a); if(a==8){ return true; }else{ return false; }