Spring 重试功能

导读:本篇文章讲解 Spring 重试功能,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

     业务系统在调用其他系统服务或者外部服务时,为防止网络抖动或其它异常因素,需要引入重试机制确保服务调用更健壮,spring 提供了spring-retry支持重试机制,废话不多说,下面直接贴代码。

    1.pom引入

<dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
            <version>1.0.2.RELEASE</version>
        </dependency>

   2. 重试调用模拟

    

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

import java.util.Random;

/**
 * spring 重试机制
 * @author test
 * @Time 2018/2/6.
 */
public class SpringRetryTest {


    /**
     * 模拟重试具体调用的方法(仅返回true则调用成功)
     * 通过随机数对基本参数求余后为3的整数则判断调用成功
     * @return
     */
    public static  boolean testRetry(int  modSeed){
        boolean  status=false;
        int randomInt=new Random().nextInt()%modSeed;
        System.out.println("当前随机数:"+randomInt);
        if(randomInt % 3==0){
            status=true;
        }
        return  status;
    }

    public static void main(String[] args) {
        RetryTemplate retryTemplate=new RetryTemplate();//重试机制
        SimpleRetryPolicy retryPolicy=new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(3);//设置最多重试次数
        retryTemplate.setRetryPolicy(retryPolicy);//设置重试策略
        FixedBackOffPolicy fixedBackOffPolicy=new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(3000l);
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);//设置重试延迟策略( 失败后多久重试)
        final  int modSeed=10;//重试参数必须为final
        try {
            Boolean obj=retryTemplate.execute(new RetryCallback<Boolean>() {
                 public Boolean doWithRetry(RetryContext retryContext) throws Exception {//重试具体方法
                     boolean isTripple= testRetry(modSeed);
                     if(!isTripple){
                         throw  new RetryException("调用服务错误");
                     }
                     //返回调用结果
                     return isTripple;
                 }
                 }, new RecoveryCallback<Boolean>() {
                     public Boolean recover(RetryContext retryContext) throws Exception {//重试多次后都失败的处理方法
                         return null;
                     }
                 }
            );
            System.out.println("服务调用结果obj:"+obj);
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }

}

   3. 测试输出结果

Spring 重试功能

   demo很简单,欢迎交流

   

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15021.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!