博主首页

spring的重试策略、发生异常会自动重新调用

测试类以及测试代码、复制即可

package com.cms.util;

import javax.swing.plaf.synth.SynthSpinnerUI;

import org.springframework.retry.RecoveryCallback;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

public class TestUtils {
    public static void main(String[] args) throws Exception {
        new TestUtils().sendMsg("", null, null);
    }
       public  void sendMsg(String msg,String phone,String[] arr) throws Exception{
               
               RetryTemplate template = new RetryTemplate();
               // 策略
               SimpleRetryPolicy policy = new SimpleRetryPolicy();
               policy.setMaxAttempts(20);
               template.setRetryPolicy(policy);
             
               ExponentialBackOffPolicy   exponen = new ExponentialBackOffPolicy();
               exponen.setInitialInterval(1000);
               exponen.setMultiplier(2);
               template.setBackOffPolicy(exponen);
               String result = template.execute(
                       new RetryCallback<String, Exception>() {
                           @Override
                           public String doWithRetry(RetryContext arg0) throws Exception {
                               try {
                                   if(1==1){
                                       System.out.println(123);
                                       throw new Exception();                                       
                                   }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                throw new Exception();
                            }
                              return "";
                           }
                       }
                       ,
                       new RecoveryCallback<String>() {
                           @Override
                           public String recover(RetryContext context) {
                               return "recovery callback";
                           }
                       }
               );
           }
}

以下是maven依赖

           <dependency>
                <groupId>org.springframework.retry</groupId>
                <artifactId>spring-retry</artifactId>
                <version>1.2.4.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                  <version>1.5.4</version>
        </dependency>

 

posted @ 2019-05-18 18:28  笑~笑  阅读(913)  评论(0编辑  收藏  举报